连接三个表并使用左外连接

时间:2011-05-26 22:40:55

标签: linq linq-to-entities linq-to-objects

我有三张桌子。其中两个平等加入,但一个人需要加入左边。我在linq中找到了很多代码,但仅在两个表之间。

这是我试图在LINQ中重新编码的SQL代码。

   SELECT PRSN.NAME
       ,CO.NAME
       ,PROD.NAME
   FROM PERSON PRSN
     INNER JOIN COMPANY CO ON PRSN.PERSON_ID = CO.PERSON_ID
     LEFT OUTER JOIN PRODUCT PROD ON PROD.PERSON_ID = PROD.PERSON_ID;

这是我用作基础的LINQ代码片段。我只是无法通过LINQ和左外连接拼凑第三个表(我的示例SQL中的产品)。样本位于两个表之间。感谢您的任何提示。

   var leftOuterJoinQuery =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID into prodGroup
    from item in prodGroup.DefaultIfEmpty(new Product{Name = String.Empty, CategoryID = 0})
        select new { CatName = category.Name, ProdName = item.Name };

迈克尔

2 个答案:

答案 0 :(得分:42)

这个怎么样:

var loj = (from prsn in db.People
           join co in db.Companies on prsn.Person_ID equals co.Person_ID
           join prod in db.Products on prsn.Person_ID equals prod.Person_ID into prods
           from x in prods.DefaultIfEmpty()
           select new { Person = prsn.NAME, Company = co.NAME, Product = x.NAME })

编辑:如果你想在所有表上做左外连接,你可以这样做:

var loj = (from prsn in db.People
           join co in db.Companies on prsn.Person_ID equals co.Person_ID into comps
           from y in comps.DefaultIfEmpty()
           join prod in db.Products on prsn.Person_ID equals prod.Person_ID into prods
           from x in prods.DefaultIfEmpty()
           select new { Person = prsn.NAME, Company = y.NAME, Product = x.NAME })

答案 1 :(得分:5)

从某个地方的另一个Stackoverflow线程中获取,这是一种更清晰的方法:

   var loj = (from prsn in db.People
           from co in db.Companies.Where(co => co.Person_ID == prsn.Person_ID).DefaultIfEmpty()
           from prod in db.Products.Where(prod => prod.Person_ID == prsn.Person_ID).DefaultIfEmpty()
           select new { Person = prsn.NAME, Company = co.NAME, Product = prod.NAME })

这使用linq查询语法和lambda语法的混合来(我相信)最好的结果。标识符没有大量的重新别名,而且这是我所见过的最简洁的方法。