2015-01-01 54 views
1

主表这是我在SQL查询:左连接2台使用LINQ

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这里给出的预期results.The的事情是,我想这相当于使用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。这里

enter image description here

指导表示赞赏。谢谢。

回答

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你可以使用任何缺省值。

+0

这将返回记录。但是一些ContactNo作为'NULL'返回,没有相应的连接行。表1中的每个记录都存在ContactNo。我想要的是,无论加入记录是否存在,contactNo在查询结束时都不应该为空。 –

+0

@iCoder - 您可以添加一个示例输入\输出吗?这会让这个更清楚。 –

+0

@HarveySpecter - 你刚刚更新了输出,没有输入就很难回答出错的地方,如果你只能显示一些示例数据(3 4条记录会这样做),而不是张贴屏幕截图,它就更好。 –