使用 DefaultIfEmpty 加入 LINQ 仍然导致 NullReferenceException

Join in LINQ with DefaultIfEmpty still causing NullReferenceException

即使有 DefaultIfEmpty() 代码,真的有可能在连接语句上引起 NullReferenceException 吗?

     var getWorkerList = (from a in workerList
                         join ps in db.ProjectStatus on a.StatusId equals ps.StatusId into hjps
                         from ps in hjps.DefaultIfEmpty()
                         join psc in db.StatusColor on ps.StatusCode equals psc.StatusCode into hjpsc
                         from psc in hjpsc.DefaultIfEmpty()
                         join lu in db.LOOKUPS on psc.StatusColorID equals lu.LOOKUPS_ID into hjlu
                         from lu in hjlu.DefaultIfEmpty()
                         select new WorkerModel()
                         {
                            FullName = a.FullName
                            ,Color = lu.LOOKUPS_Code                  
                         }).OrderBy(a => a.WorkerId).ToList();

这是我得到 NullReferenceException 错误的地方:

join lu in db.LOOKUPS on psc.StatusColorID equals lu.LOOKUPS_ID into hjlu
                         from lu in hjlu.DefaultIfEmpty()

添加此连接语句时出现错误。请帮忙。

.DefaultIfEmpty() returns 具有单个默认值的序列如果原始源为空

它仍然会抛出空引用异常,如果原始源为空

你正在使用 'left join' 而不是 '.DefaultIfEmpty()'

'join'

因此您必须更正 select 语句:将 'Color = lu.LOOKUPS_Code' 替换为:'Color = lu == null ? "" : lu.LOOKUPS_Code'.

您还可以使用“.DefaultIfEmpty()”的不同重载来设置替换而不是 'null',这样 select 语句就不会抛出异常