2013-12-22 131 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 ;