从左连接中选择时出现NullReferenceException

时间:2016-07-18 07:07:52

标签: c# sql linq join

我正在尝试做2个左连接。我已在SQL服务器中测试了查询,但它可以工作,但我无法在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
            };

我正在

  

对象引用未设置为对象的实例。

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

1 个答案:

答案 0 :(得分:4)

拥有left join意味着如果第二个表中没有匹配的记录,那么所有这些值都是null(与普通join不同,它不会返回记录左表)。你可能有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的使用情况