c# - 从左连接中选择时出现 NullReferenceException

标签 c# sql linq join

我正在尝试进行 2 次左连接。我已经在 SQL Server 中测试了查询并且它可以工作,但是我无法在 linq 中重新创建查询。

查询:

select Master.InvoiceId,Consumer.ConsumerId,ConsumerCharge.ChargeId , Amount 
from Master 

left outer join  Consumer on 
Master.InvoiceId=Consumer.InvoiceId 

left outer join ConsumerCharge on 
Consumer.ConsumerId = ConsumerCharge.ConsumerId and 
Consumer.InvoiceId = ConsumerCharge.InvoiceId and 
Master.InvoiceId = ConsumerCharge.InvoiceId

order by InvoiceId

在 LINQ 中:

var query = from m in IM.GetMaster()

            join co in CM.GetConsumers()
            on m.InvoiceId equals co.InvoiceId into temp2
            from co in temp2.DefaultIfEmpty()

            join ch in CCM.GetCharge()
            on new { co.InvoiceId, co.ConsumerId,  } equals new { ch.InvoiceId, ch.ConsumerId }   into temp
            from ch in temp.DefaultIfEmpty()

            orderby m.InvoiceId
            select new
            {
                InvioceID = m.InvoiceId,
                ConsumerID = co == null ? 0 : co.ConsumerId,
                ChargeID = ch == null ? 0 : ch.ChargeId,
                Amount = ch == null ? 0 : ch.Amount
            };

我得到了

Object reference not set to an instance of an object.

在新 { co.InvoiceId, co.ConsumerId, } 的 行。如果我从 temp2.​​DefaultIfEmpty() 中的 co 中删除 into temp2,它会显示,但不会显示没有任何消费者 ID 的发票 ID。如何在涉及 3 个表的情况下进行正确的左连接?

最佳答案

left join 意味着如果第二个表中没有匹配的记录,那么所有这些值都是null(不同于普通的join code> 它不会返回左表中的记录)。你可能有 co 等于 null 该记录所以你必须检查它

试试这个:

var query = from m in IM.GetMaster()

        join co in CM.GetConsumers()
        on m.InvoiceId equals co.InvoiceId into temp2
        from co in temp2.DefaultIfEmpty()

        join ch in CCM.GetCharge()
        on new { co?.InvoiceId, co?.ConsumerId,  } equals new { ch?.InvoiceId, ch?.ConsumerId }   into temp
        from ch in temp.DefaultIfEmpty()

        orderby m.InvoiceId
        select new
        {
            InvioceID = m.InvoiceId,
            ConsumerID = co?.ConsumerId,
            ChargeID = ch?.ChargeId,
            Amount = ch?.Amount
        };

另请参阅 ?. 在您的 select new 中的使用

关于c# - 从左连接中选择时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38430511/

相关文章:

c# - 当取消请求返回 true 时如何做 sthg?

c# - Linq - 分组然后比较每个组内的元素

c# - 使用传入两个参数的linq查询实体

c# - 如何使用 LINQ Contains(string[]) 而不是 Contains(string)

sql - Postgresql:检查列是否同时等于多个值的最佳方法

c# - 异步编程像僵尸病毒吗?

c# - IIS 10.0 详细错误 - 404.0 - 未找到 - Windows 10 更新后

c# - ASP.net 创建图像

c# - 无法为表中的标识列插入显式值

sql - 具有重复元素的动态 SQL 查询