将正常的SQL查询转换为涉及多个LEFT OUTER JOINS的LINQ查询而苦苦挣扎..
原始SQL查询:
SELECT a.*
FROM Testers t
LEFT OUTER JOIN Users u ON u.TesterId = t.TesterId
LEFT OUTER JOIN ValidForms v ON v.DepartmentId = u.DepartmentId
LINQ查询代码如下:
var x = (from t in Context.Testers.AsEnumerable()
from u in Context.Users
.Where(a => a.TesterId == t.TesterId)
.DefaultIfEmpty()
from v in Context.ValidForms
.Where(b => b.DepartmentId == u.DepartmentId)
.DefaultIfEmpty()
Select new myEntity
{
col1 = t.col1,
col2 = t.col2
}).AsEnumerable()
return x.ToList();
运行查询,我收到错误:非静态方法需要目标
感谢是否有人可以在LINQ中指出如何正确地进行查询。
我还检查了此处发布的SO问题,但我无法理解所提供的概念:SQL to Linq query with multiple left outer joins
感谢。
更新: 我从SO question得到了这个。
答案 0 :(得分:0)
This is a good way to do it.如果您遵循该示例,您的代码应如下所示:
var x = (from t in Context.Testers.AsEnumerable()
join u in Context.Users on t.TesterId equals u.TesterId into group1
from a in group1.DefaultIfEmpty()
join v in Context.ValidForms on a.DepartmentId equals v.DepartmentId into group2
from b in group2.DefaultIfEmpty()
select new MyEntity {
col1 = b.col1,
col2 = b.col2
}).AsEnumerable();
<强>已更新强>
var x = (from t in Context.Testers.AsEnumerable()
join u in Context.Users on t.TesterId equals u.TesterId
join v in Context.ValidForms on u.DepartmentId equals v.DepartmentId into group1
from b in group1.DefaultIfEmpty()
select new MyEntity {
col1 = (b != null) ? b.col1 : null,
col2 = (b != null) ? b.col2 : null
}).AsEnumerable();