2013-05-28 176 views
2

我怎樣才能在linq中寫這個查詢?Linq多個加入同一張表

select * from bills as b inner join customer as c1 
      On b.shipperID=c1.CustomerID inner join customer c2 
      On b.ConsigneeID=c2.CustomerID  
--------------------------- 

我需要它,如下:

var result=from p1 in entities.bills 
      join p2 in entities.customer on p1.shipperID equals p2.customerID 
      join p3 in entities.customer on p1.consigneeID equals p3.customerID 
      select p2; 
      return resuls.Tolist() 

謝謝:)

回答

2

在SQL你選擇所有所以在LINQ你需要把所有的對象在新的匿名類型如下。

var result = from p1 in entities.bills 
      join p2 in entities.customer on p1.shipperID equals p2.customerID 
      join p3 in entities.customer on p1.consigneeID equals p3.customerID 
      select new 
       { 
        Bills = p1, 
        Shippers = p2, 
        Consignees = p3 
       }; 

      return resuls.Tolist(); 

或者如果你需要他們flattened你必須投資他們屬性的財產。

你應該使用LINQ導航屬性,像

from bills in entities.bills 
select new 
{ 
    bills.Shipper 
    bills.Consignee 
}; 
+0

山姆,你是最棒的,我會在利茲足球隊的球迷:) –