【问题标题】:Linq multiple join on same table同一张表上的Linq多重连接
【发布时间】:2013-05-23 20:57:39
【问题描述】:

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

谢谢:)

【问题讨论】:

    标签: linq entity inner-join


    【解决方案1】:

    在您的 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
    };
    

    【讨论】:

    • 山姆,你是最棒的,我会成为利兹足球队的球迷:)
    猜你喜欢
    • 2015-05-18
    • 2015-07-24
    • 1970-01-01
    • 2016-03-07
    • 2011-10-18
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    相关资源
    最近更新 更多