EF4级联左外部连接空例外

时间:2011-09-19 22:06:03

标签: entity-framework-4

我有这个查询

Select p.Name,p.Street from person p
left join address a on a.address_id = p.address_id
left join Order o on o.order_id = a.order_id

但是当我尝试将其转换为LINQ查询时,

var q = from p in Entities.Person 
        from a in Entities.Address.Where(a=>a.address_id == p.address_id).DefaultIfEmpty()
        from o in Entities.Order.Where (o=>o.order_id== a.order_Id).DefaultIfEmpty()

我得到一个Null异常,因为对于address_ids的某些组合,没有地址,并且它在o => o.order_id == a.order_Id子句中爆炸(因为a为null)。

请告诉我如何以正确的方式在EF 4中进行多次左连接!

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您已正确建模,则无需显式执行左外连接。

Select p.Name, a.Street from person p
left join address a on a.address_id = p.address_id
left join Order o on o.order_id = a.order_id

上述查询可以转换如下

var projection = Entities.Person.Select(p => new {p.Name, p.Address.Street});

EF会自动添加联接以检索字段。

您可以按如下方式手动执行连接

 var projection = from p in Entities.Person
        join a in Entities.Address on p.address_id equals a.address_id into outer
        from a in outer.DefaultIfEmpty()
        select new {p.Name, a.Street};