Thursday, August 2, 2012

How to write a left outer join in LINQ?

This can be accomplished by using DefaultIfEmpty(). See the example LINQ query below:

var provQuery = (from a in entities.Table1
                join c in entities.Table2 on a.ID equals c.ID into temppvcon
                from t2 in temppvcon.DefaultIfEmpty()
                where a.ID == Id
                select new { a.ID, a.NAME, t2.ID, t2.NAME });


Check out the SQL generated from the above LINQ query:

SELECT
1 AS "C1",
"Extent1"."ID" AS "ID",
"Extent1"."NAME" AS "NAME",
"Extent2"."ID" AS "ID",
"Extent2"."NAME" AS "NAME"
FROM  (SELECT
      "TABLE1"."ID" AS "ID",
      "TABLE1"."CON_ID" AS "CON_ID",
      "TABLE1"."NAME" AS "NAME",
      "TABLE1"."ADDED_DT" AS "ADDED_DT"
      FROM "DB"."TABLE1" "TABLE1") "Extent1"
LEFT OUTER JOIN (SELECT
      "TABEL2"."NAME" AS "NAME",
      "TABEL2"."PART" AS "PART",
      "TABEL2"."ID" AS "ID",
      "TABEL2"."CLUSTER_ID" AS "CLUSTER_ID"
      FROM "CDCDATA"."TABEL2" "TABEL2") "Extent2" ON "Extent1"."ID" = "Extent2"."ID"
WHERE ("Extent1"."ID" = :p__linq__0)


Hope this is clear. Enjoy...

How to view the SQL generated by LINQ to Entities?

There is a ToTraceString() method for objectQuery. The anonymous object returned from the LINQ query has to be casted into ObjectQuery as shown below to use the ToTraceString():

var provQuery = from a in entities.Table1 where a.ID == id orderby a.Name
                            select a;

The SQL generated from the LINQ can be viewed by using as below:

((System.Data.Objects.ObjectQuery)provQuery).ToTraceString()

You can copy from watch window and run the sql query to test it.