我正在尝试找出多个左连接的LINQ
语法,但我收到错误:The name 'c' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.
我已经尝试过交换,如果我这样做,它会使得这两个问题都得到了解决。并且' d'有"不在范围"错误。
var result =
from a in db.tableA
join b in db.tableB //first join (inner join)
on a.field1 equals b.field1
join c in db.tableC //second join (left join)
on a.field1 equals c.field1
into left_one
join d in db.tableD //third join (left join)
on c.field2 equals d.field2
// ^ here
into left_two
where a.field1 == theValueImSearchingFor
from c in left_one.DefaultIfEmpty()
from d in left_two.DefaultIfEmpty()
select new CombinedObject()
{
...
}
我在第三个连接语句中使用on c.field2 equals d.field2
的原因是我的表结构如下:
tableA: field1
tableB: field1
tableC: field1 field2
tableD: field2
也就是说,将tableD与其他数据相关联的唯一方法是使用field2
。
有人可以更正我的语法吗?或者,根据我的表格设置,我是否有必要这样做?
答案 0 :(得分:8)
我使用这种语法:
var results = (from a in db.tableA
from b in db.tableB.Where(s => s.field1 == a.field1)
from c in db.tableC.Where(s => s.field1 == a.field1).DefaultIfEmpty()
from d in db.tableD.Where(s => s.field2 == c.field2).DefaultIfEmpty()
select new CombinedObject() { });
它似乎在多个表上运行良好。我想我的field1s和field2s正确匹配你的例子:)
[编辑]
根据评论,如果您想添加一些额外的过滤,只需将其添加到Where()
中。例如:
from c in db.tableC.Where(s => s.field1 == a.field1 && s.field3 == someVariable).DefaultIfEmpty()
类似的东西:)