ASP.NET MVC按登录UserId拆分Participant列表及空引用错误解决咨询
问题原因
你遇到的空引用异常是因为EF Core默认不会自动加载导航属性,你查询League数据时没有显式加载child关联的Parent属性,导致访问mmLeagueParticipant.child.Parent时为null,触发报错。
另外你完全不需要访问Parent导航属性拿用户ID,你的Participant模型本身已经定义了外键字段UserId,这个字段会在查询Participant数据时直接返回,不需要加载关联的User表,既省性能又能规避空引用问题。
解决方案
直接修改视图中的判断逻辑,用Participant自带的UserId字段匹配即可,同时处理ViewBag.UserId的可空类型问题:
@model List<League> @{ if (Model != null && Model.Any()) { // 先把当前用户ID转成非空int,避免可空类型比较异常 int currentUserId = ViewBag.UserId ?? 0; <p>您的孩子:</p> foreach(League i in Model) { foreach (MMLeagueParticipant mmLeagueParticipant in i.allParticipants) { if(mmLeagueParticipant.child.UserId == currentUserId) { <p>@mmLeagueParticipant.child.ParticipantFirstName @mmLeagueParticipant.child.ParticipantLastName</p> } } } <p>其他孩子:</p> foreach(League i in Model) { foreach (MMLeagueParticipant mmLeagueParticipant in i.allParticipants) { if(mmLeagueParticipant.child.UserId != currentUserId) { <p>@mmLeagueParticipant.child.ParticipantFirstName @mmLeagueParticipant.child.ParticipantLastName</p> } } } } else { <p>列表为空</p> } }
扩展说明(如果需要用到Parent的其他属性)
如果后续业务需要访问Parent的姓名、邮箱等其他属性,你需要在控制器查询League数据时显式加载多层导航属性:
// 控制器查询代码示例 var leagueList = _context.Leagues .Include(l => l.allParticipants) .ThenInclude(mm => mm.child) .ThenInclude(c => c.Parent) .ToList(); return View(leagueList);
显式Include之后,Parent导航属性就会有值,不会再抛出空引用异常。
内容的提问来源于stack exchange,提问作者jgrewal
相关产品推荐
相关产品推荐

