使用扩展方法linq创建左连接和内连接查询

时间:2013-03-07 16:14:01

标签: linq linq-to-sql

    select *
From Item i inner join Order o on i.OrderId = o.Id
        left join OrderDealersByDistance d on o.Id = d.OrderId
        left join SubOrder s on i.SubOrderId = s.Id
where d.[Status] = 1

我想用实体框架写上面的查询。我更喜欢DataContext和扩展方法。我怎样才能写上面的查询?

1 个答案:

答案 0 :(得分:0)

首先,我会使用查询语法,因为它更具可读性。

它看起来像这样

var db = new MyDbContext(conStr);

var query = from i in db.Items
     from o in db.Orders.Where(o => o.Id == i.OrderId)
     from d in db.OrderDealersByDistance.Where(d => d.OrderId == o.Id).DefaultIfEmpty()
     from s in db.SubOrders.Where(s => i.SubOrderId == s.Id).DefaultIfEmpty()
     where d.Status == 1
     select new { Item = i, Order = o, c.ContractName, Distance = d, SubOrder = s };

var result = query.ToList();

DefaultIfEmpty()方法为您提供左连接。 您可能希望更具体地了解选择列表(命名列而不是'*')。