Linq多次加入同一个表

pet*_*ova 2 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      
---------------------------
Run Code Online (Sandbox Code Playgroud)

我需要如下:

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()
Run Code Online (Sandbox Code Playgroud)

谢谢:)

Sam*_*ach 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();
Run Code Online (Sandbox Code Playgroud)

或者,如果你需要它们扁平化,你将不得不按属性投射它们.

您应该在LINQ中使用导航属性,例如

from bills in entities.bills
select new
{
    bills.Shipper
    bills.Consignee
};
Run Code Online (Sandbox Code Playgroud)