使用Linq执行多个左连接

时间:2014-04-24 11:30:11

标签: linq join

我有四张桌子。我想在表上执行多个左连接,如下所示。

from t1 in table1
join t2 in table2 on <condition1>
into join1
from subJoin1 in join1.DefaultIfEmpty()
join t3 in table3 on <condition2>
into join2
from subjoin2 in join2.DefaultIfEmpty()
join t4 in table4 on <condition3>
into join3
from subjoin3 in join3.DefaultIfEmpty()
select new

{
Field1 = t1.some_field,
Field2 =  t2.some_field,
Field3 =  t3.some_field,
Field4 =  t4.some_field,
}

我的问题是第一个左连接单独工作正常,但是当左连接连续完成时,如果在t3,t4等中找不到映射,则t1数据行会丢失。

请帮忙。

1 个答案:

答案 0 :(得分:0)

您不需要into(至少马上就开始)!

这样的东西
from t1 in table1
join t2 in table2 on <inner_join_condition>
from t3 in table3.Where(<left_outer_join_condition>).DefaultIfEmpty()
...
select new
{
Field1 = t1.some_field,
Field2 = t3.some_field,
...
}

通常效果很好!