我正在尝试进行 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/