2013-12-22 127 views
5

我有一个SQL查询来处理像这样的Lambda表达式,通常比这个例子中有更多的连接。用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 

我这样做是与加入()Lambda表达式,但我SQL Server Profiler中看到,这产生INNER JOIN,我需要一个LEFT OUTER 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()或群组加入(做),但我还没有发现任何复杂的例子多于一个左外连接。

+0

你能显示你有哪些导航属性?当你使用像'orderby table1.Table3.f'这样的语法时,这非常容易。 –

+0

您好,我的lambda表达式dos没有指出它,因为我希望实体的所有字段都是lambda表达式结尾处的select的原因。 – JuanDYB

+0

既然你知道如何用左连接编写查询语句,为什么不直接调用它,或者把它放在存储过程中并调用它呢? – HLGEM

回答

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 ;