我确信这之前已经讨论过,但我阅读了几篇 LINQ 左外部连接帖子,无法弄清楚它是否已经讨论过。与我正在寻找的最接近的线程是Replace returned null values in LEFT OUTER JOIN,但它与 LINQ 无关。
现在谈谈我的问题,我的查询确实使用 DefaultIfEmpty() 进行了左外连接。这是我从另一篇文章中获取的示例查询以进行说明
from adx_event in Adx_eventSet
join adx_eventsponsor in adx_eventsponsor_eventSet
on adx_event.Adx_eventId equals adx_eventsponsor.adx_eventid into j
from adx_eventsponsor in j.DefaultIfEmpty()
select new
{
Name = adx_event.Name,
Name = adx_eventsponsor != null ? adx_eventsponsor.Name : null
};
在上述查询中,如果 adx_eventsponsor 返回 null,则检查“对 adx_event.Adx_eventId 等于 adx_eventsponsor.adx_eventid 到 j”的检查失败并出现 Null 引用异常。如何处理这个问题?
这是我正在使用的查询,抱歉,它的查询很长,有 5 个左连接
from t1 in table1List
join t2 in table2List on t1.ID equals t2.fID
join m in DataAccess.Data.table3List on t2.ID equals m.ID into fg
from fgi in fg.Where(m => m.Year == reportYear).DefaultIfEmpty()
join c1 in table4List on t2.ID equals c1.ID into t4
from c1 in t4.Where(c1 => c1.Year == reportYear && c1 != null).DefaultIfEmpty()
join c2 in table4List on t2.ID equals c2.ID into t5
from c2 in t5.Where(c2 => c2.Year == reportYear - 1).DefaultIfEmpty()
join fA in table5List on t2.ID equals fA.ID into t6
from fA in t6.Where(fA => fA.Year == reportYear).DefaultIfEmpty()
join src in table6List on new { ID = fA != null ? fA.sourceID :
new Guid(" {ccae20792ebc-4200-879d-866fc82e6afa}"), Year = reportYear } equals new
{ ID = Src.ID, Year = Src.Year } into t7 from Src in t7.DefaultIfEmpty()
我的问题是在最后一个左外连接中,如果 fA(来自 table5List)返回 null,我不能对 fA.sourceID 进行连接,所以我明确地对 Guid 进行硬编码以避免该 null 异常。有什么更好的方法来做到这一点?
谢谢你的帮助!