EF Core关联查询关联表数据及空引用异常解决求助
解决NullReferenceException并正确加载关联数据
嗨,我来帮你搞定这个问题!你遇到的NullReferenceException是因为在加载ParentReferences的时候,没有同时加载它关联的ParentBGItem和ChildBGItem实体,导致在视图中访问这些属性时它们是null。
问题分析
EF Core 默认不会自动加载关联实体(除非开启了延迟加载,但在Razor Pages场景下,上下文通常在OnGetAsync执行完成后就被释放了,延迟加载会失效)。你当前的代码只Include了ParentReferences和它的ReferenceType,但没IncludeParentBGItem和ChildBGItem,所以在视图里访问@item.ParentBGItem.BGIName或者想获取子项名称时就会抛出空引用异常。
解决方案
修改你的OnGetAsync方法,在IncludeParentReferences和ChildReferences的同时,通过ThenInclude加载它们关联的ParentBGItem、ChildBGItem实体:
public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } BusinessGlosItem = await _context.businessGlosItem .Include(x => x.BusinessArea) .Include(x => x.BusinessGlosItemStatus) // 加载ChildReferences及其关联的所有实体 .Include(x => x.ChildReferences) .ThenInclude(r => r.ReferenceType) .Include(x => x.ChildReferences) .ThenInclude(r => r.ParentBGItem) .Include(x => x.ChildReferences) .ThenInclude(r => r.ChildBGItem) // 加载ParentReferences及其关联的所有实体 .Include(x => x.ParentReferences) .ThenInclude(r => r.ReferenceType) .Include(x => x.ParentReferences) .ThenInclude(r => r.ParentBGItem) .Include(x => x.ParentReferences) .ThenInclude(r => r.ChildBGItem) .Include(x => x.businessGlosItemComments) .SingleOrDefaultAsync(m => m.Id == id); if (BusinessGlosItem == null) { return NotFound(); } return Page(); }
视图代码修正
另外,你的视图里当前写的是@item.ChildGlosItemId,这只是ID,你需要显示子项名称,同时为了避免ChildBGItem为null时再次抛出异常,建议使用空传播运算符(?.):
@foreach (var item in Model.BusinessGlosItem.ParentReferences) { <tr> <td>@item.ReferenceType?.ReferenceTypeName</td> <td>@item.ParentBGItem?.BGIName</td> <td>@item.ChildBGItem?.BGIName</td> <!-- 改为子项名称,添加空传播运算符 --> </tr> }
补充说明
- 如果你开启了延迟加载(需要安装
Microsoft.EntityFrameworkCore.Proxies并在上下文配置中启用),虽然可能暂时解决问题,但在Razor Pages中由于上下文生命周期的问题,很容易出现类似的空引用或ObjectDisposedException,所以显式Include是更可靠的做法。 - 使用空传播运算符(
?.)可以在实体为null时返回null而不是抛出异常,让页面更健壮。
内容的提问来源于stack exchange,提问作者xcelm
相关产品推荐
相关产品推荐

