我确信之前已经讨论过这个问题,但我读了几个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,则检查“on 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异常。有什么更好的方法呢?
感谢您的帮助!