代码之家  ›  专栏  ›  技术社区  ›  Ralph Shillington

如何获取Linq查询的outerjoin

  •  0
  • Ralph Shillington  · 技术社区  · 14 年前

    给出这个linq查询

    from c in context.Customers
    from o in c.Orders
    where c.City == "MyCity" || o.ShipTo == "MyCity"
    select c
    

    在这种情况下,我需要客户和订单之间的外部连接。我该怎么在林肯表达呢?我认为TSQL的近似值是

    select customers.* 
    from customers 
    left join orders on customers.id = orders.customerid
    where customers.city = 'MyCity' or orders.ShipTo = 'MyCity'
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Community    7 年前

    要获取外部联接,可以使用DefaultIfEmpty。请看这个问题: Linq to Sql: Multiple left outer joins

    from c in context.Customers
    from o in context.Orders
        .Where(a => a.customerid == c.id)
        .DefaultIfEmpty()
    where c.City == "MyCity" || o.ShipTo == "MyCity"
    select c
    

    或者,您可以执行以下操作:

    from c in context.Customers
    join o in context.Orders on c.id equals o.customerid into g
    from x in g.DefaultIfEmpty() 
    where c.City == "MyCity" || x.ShipTo == "MyCity"
    select c
    

    我相信它们都生成相同的SQL。

        2
  •  0
  •   codingbadger    14 年前

    你必须使用 DefaultIfEmpty

    var result = from c in context.Customers
        join o in c.Orders on c.CustomerId equals o.CustomerId into lj
        from or in lj.DefaultIfEmpty()
        where c.City == "MyCity" || or.ShipTo == "MyCity"
        select c