我花了最近两天试图找出如何在LINQ中进行真正的LEFT JOIN并且我没有成功.
@H_403_2@我有一个用户表,其中有一个“Primary2Address”列,可能并且通常为NULL.
@H_403_2@所以我必须在这里进行LEFT JOIN.另外,在Address表中,我有更多可能为NULL的关系,所以我必须做多个LEFT JOINS.
@H_403_2@每次LINQ尝试我都会使用UNIONS输出一些严重的CRAZY sql语句,嵌套的SELECT语句和更多古怪的东西.
@H_403_2@我只需要:
SELECT u.UserName FROM Users u LEFT JOIN Addresses a ON a.AddressiD = u.Primary2Address LEFT JOIN States s ON s.StateID = a.Address2State LEFT JOIN Countries c ON c.CountryID = a.CountryID
请帮忙!到目前为止,我的解决方法是创建一个使用上面的sql语句的存储过程,但我真的想尝试使用LINQ(L2E).@H_403_2@多谢你们!
解决方法
DefaultIfEmpty用于EntityFramework 4的左连接
var query = from u in context.Users from a in context.Addresses .Where(x => u.Primary2Address == x.AddressiD) .DefaultIfEmpty() from s in context.States .Where(x => a.Address2State == x.StateID) .DefaultIfEmpty() from c in context.Countries .Where(x => a.CountryID == x.CountryID) .DefaultIfEmpty() select u.UserName;