我正在研究一个linq查询,它有一个涉及可空列的左连接。此加入是在 BackgroundColors 表格与int
ID 列之间以及名为 MenuFolders 的表格之间进行的,该表格具有{{ 1}}列名为 BackgroundColorId 。在 MenuFolders 中,每一行的BackgroundColorId都设置为int?
。
我的查询中的每个左连接都可以正常工作到这两个表的连接。当我使用menuFolders取消注释backgroundColors左连接时,查询会生成NullReferenceException - “对象引用未设置为对象的实例。”但我认为null
应该照顾那。这是我的代码。请记住,在SQL Server上运行SQL等效工作正常:
.DefaultIfEmpty()
我也尝试使用标准linq而不是lambda表达式来执行此查询,但它仍然给出了同样的错误。
我之前看过这个链接,以帮助回答这个问题,但它的答案对我不起作用: LINQ Join query (with nullable ref between table)
编辑:我尝试将 BackgroundColorId 列中的值从 var folderStructure = (from fa in folderAncestorsLanguage
from mf in menuFolders.Where(x => x.Id == fa.Id)
from mtf in menuTlbrMenuFolders.Where(x => (x.MenuToolbarId == toolbarId && x.MenuFolderId == fa.Id)).DefaultIfEmpty()
from mbc in backgroundColors.Where(x => x.Id == mf.BackgroundColorId).DefaultIfEmpty()//Left Join that is causing an exception
from lmf in languageMenuFolders.Where(x => x.MenuFolderId == mf.Id).DefaultIfEmpty()
where (mf.StatusId == 1)
select new
{
Id = mf.Id,
Name = lmf.Name,
DefaultName = mf.Name,
Description = mf.Description,
FolderId = fa.ParentFolderId,
OrderIndex = mf.OrderIndex,
IconUrl = mf.IconUrl,
IsFramework = mf.IsFramework,
BackgroundColor = mbc.HexCode == null ? null : mbc.HexCode,
IsModifiable = mf.IsModifiable,
iconCls = mf.iconCls
}).ToList();
更改为整数值,但我仍然遇到相同的错误。
答案 0 :(得分:3)
var folderStructure = (from fa in folderAncestorsLanguage
from mf in menuFolders.Where(x => x.Id == fa.Id)
from mtf in menuTlbrMenuFolders.Where(x => (x.MenuToolbarId == toolbarId && x.MenuFolderId == fa.Id)).DefaultIfEmpty()
from mbc in backgroundColors.Where(x => x.Id == mf.BackgroundColorId).DefaultIfEmpty()//Left Join that is causing an exception
from lmf in languageMenuFolders.Where(x => x.MenuFolderId == mf.Id).DefaultIfEmpty()
where (mf.StatusId == 1)
select new
{
Id = mf.Id,
Name = (lmf == null) ? null : lmf.Name,
DefaultName = mf.Name,
Description = mf.Description,
FolderId = fa.ParentFolderId,
OrderIndex = mf.OrderIndex,
IconUrl = mf.IconUrl,
IsFramework = mf.IsFramework,
BackgroundColor = (mbc == null) ? null : mbc.HexCode,
IsModifiable = mf.IsModifiable,
iconCls = mf.iconCls
}).ToList();
我最终想通了,我的一些连接导致表格虽然它们不是空的,但是我引用的是行,因此导致异常。希望如果他们遇到这个问题,这会帮助其他人。