Linq多次加入同一个表

时间:2013-05-28 19:13:54

标签: linq entity inner-join

如何在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()

感谢:)

1 个答案:

答案 0 :(得分:5)

在你的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();

或者如果你需要将它们弄平,你将不得不按属性投射它们。

你应该在LINQ中使用导航属性,比如

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