2014-09-19 87 views
0

我想在Linq to Sql查詢中使用兩個或多個表執行左連接,但是看起來在C#中沒有這樣做的關鍵字。有沒有什麼辦法像我們使用Linq to Sql進行內部連接一樣執行左連接?如何使用LInq中的兩個或多個表執行左連接以查詢Sql?

public IQueryable GetProducts(int productID) 
{ 
    var products = 
     from p in this.Products 
     left join c in this.ProductCategoryProducts 
     on p.CategoryID equals c.ProductCategoryID 
     left join ac in this.ProductCategories 
     on c.ProductCategoryID equals ac.ProductCategoryID 
     where p.ProductID == productID 
     select new 
     { 
      ProductID = a.ProductID, 
      Heading = p.Heading,     
      Category = ac.ProductCategory 
     }; 
    return products ; 
} 
+1

'DefaultIfEmpty()'是招左外Linq中的聯接。看到這個http://msdn.microsoft.com/en-us/library/bb397895.aspx – 2014-09-19 13:31:50

+0

檢查這個答案是一個很好的解釋組加入http://stackoverflow.com/a/15599143/2617732 – rdans 2014-09-21 10:53:14

回答

0

反正我這樣使用Lambda表達式的解決方案:

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

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

     where p.ProductID == productID 
     select new 
     { 
      ProductID = p.ProductID, 
      Heading = p.Heading,     
      Category = pc.ProductCategory 
     }; 
    return products ; 
0
public IQueryable GetProducts(int productID) 
{ 
    var products = 
     from p in this.Products 
     join c in this.ProductCategoryProducts 
     on p.CategoryID equals c.ProductCategoryID into pclj 
     from pc in pclj.DefaultIfEmpty() 
     join ac in this.ProductCategories 
     on c.ProductCategoryID equals ac.ProductCategoryID into pcidlj 
     from pcid in pcidlj.DefaultIfEmpty() 
     where p.ProductID == productID 
     select new 
     { 
      ProductID = p.ProductID, 
      Heading = p.Heading,     
      Category = pcid != null ? pcid.ProductCategory : null 
     }; 
    return products ; 
}