【问题标题】:Left Join 2 tables with main table using LINQ使用 LINQ 将 2 个表与主表左连接
【发布时间】:2015-02-28 02:05:57
【问题描述】:

这是我的 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

感谢您的指导。谢谢。

【问题讨论】:

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


    【解决方案1】:

    您的查询在我看来很好,您必须获得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你可以使用任何默认值。

    【讨论】:

    • 这将返回记录。但是一些 ContactNo 被返回为NULL,没有相应的连接行。表 1 中的每条记录都存在 ContactNo。我想要的是无论加入记录是否存在,查询结束时的contactNo都不应该为null。
    • @iCoder - 你能添加一个示例输入\输出吗?这样会更清楚。
    • @HarveySpecter - 您刚刚更新了输出,没有输入真的很难回答出了什么问题,如果您可以只显示一些示例数据(3 4 条记录就可以),而不是发布截图。
    • 您指出了正确的方向。我只记得这个问题是为了把它作为答案。谢谢你。非常感激。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多