使用lambda表达式的多个左外连接

时间:2013-12-22 12:20:31

标签: c# sql sql-server entity-framework lambda

我有一个SQL查询与这样的Lambda表达式有关,通常连接数多于此示例。

select Table2.a,
          Table2.b,
          Table2.c,
          Table2.d
   from Table1
     LEFT OUTER JOIN Table2
     ON Table2.a = Table1.a and
        Table2.b = Table1.b and
        Table2.c = Table1.c 
     LEFT OUTER JOIN Table3
     ON Table3.b = Table1.b AND
        Table3.c = Table1.c AND
        Table3.d = Table1.d 
   where ( Table1.a = ValueA )
   order by Table3.f

我正在使用Join()Lambda Expression执行此操作,但我在SQL Server分析器中看到这会生成INNER JOIN,我需要LEFT OUTER JOIN。

这就是我用Join()

做的
var RS = DBContext.Table1.Join(DBContext.Table2,
  Table1 => new {Table1.a, Table1.b, Table1.c},
  Table2 => new {Table1.a, Table1.b, Table1.c},
  (Table1, Table2) => new {Table1})
.Join(DBContext.Table3,
  LastJoin => new {LastJoin.Table1.b, LastJoin.Table1.c, LastJoin.Table1.d},
  Table3 => new {Table3.b, Table3.c, Table3.d},
  (LastJoin,Table3) => new {LastJoin.Table1, Table3})
.Where (LastTable => LastTable.Table1.a == ValueA)
.OrderBy(LastTable => LastTable.Table3.f)
.Select (LastTable => new {LastTable.Table1, LastTable.Table3});

我一直在读它可以使用DefaultIfEmpty()或GroupJoin()来完成,但我找不到任何带有多个LEFT OUTER JOIN的复杂示例。

1 个答案:

答案 0 :(得分:3)

为什么不尝试使用linq查询,与lambda表达式相比,编写和理解它们也容易得多。我有这样的实现,如:

var products = 
        from p in this.Products
        from cat in this.ProductCategoryProducts
        .Where(c => c.ProductID == p.ProductID).DefaultIfEmpty()

        from pc in this.ProductCategories 
        .Where(pc => ac.ProductCategoryID == cat.ProductCategoryID).DefaultIfEmpty()

        where p.ProductID == productID
        select new
        {
            ProductID = p.ProductID,
            Heading = p.Heading,                
            Category = pc.ProductCategory
        };
    return products ;