使用LINQ将主表连接到2个表

时间:2015-01-01 11:27:28

标签: c# asp.net linq asp.net-mvc-4 sql-to-linq-conversion

这是我在SQL中的查询:

Select distinct * from tr.Table1 
Left Outer join tr.Table2 on tr.Table1.ID = tr.Table2.ID
Left Outer join tr.Table3 on tr.Table2.AId= tr.Table3.ID
where tr.Table1.Deleted =1 and tr.Table1.Ready=1 and tr.Table1.Show=0

查询在SQL中工作并给出了预期的结果。这里的事情是我希望使用LINQ等效。我在LINQ查询中尝试了一些变体,例如:

var query = from p in _ctx.Table1
join s in _ctx.Table2 on p.Id equals s.Id into bag1
from to in bag1.DefaultIfEmpty()
join tx in _ctx.Table3 on to.AId equals tx.Id into bag2
from ts in bag2.DefaultIfEmpty()
select new
{
    ContactNo = to.Table1.ContactNo
};

但它始终不会返回所有字段值。有些作为NULL返回。还尝试引用其他一些链接,但它们都专注于与父表连接,而我必须将其中一个连接表与另一个连接。所以我在这里努力奋斗。

这是我现在得到的输出。某些值为null。该字段具有值,但由于某些加入问题,它们将返回为NULL

enter image description here

这里的指导表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:2)

你的查询看起来很好,你必须获得Nulls的原因是因为当我们使用DefaultIfEmpty时,它会为不匹配的行返回null,因此你需要处理获取实际结果。尝试做这样的事情: -

var query = from p in _ctx.Table1
join s in _ctx.Table2 on p.Id equals s.Id into bag1
from to in bag1.DefaultIfEmpty()
join tx in _ctx.Table3 on to.AId equals tx.Id into bag2
from ts in bag2.DefaultIfEmpty()
select new
{
    ContactNo = to == null ? String.Empty  : to.Table1.ContactNo
};

假设ContactNo是String类型,我使用String.Empty你可以使用任何默认值。

相关问题