You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 5.0环境下Razor页面获取Product与ProductComments一对多关联数据时出现空引用错误求助

解决Product关联ProductComments时的空引用错误

我来帮你分析下出现空引用错误的核心原因,以及对应的解决方案:

问题根源分析

从你的代码来看,主要有两个关键问题:

  1. 实体关联属性定义错误:Product和ProductComment是一对多关系,所以Product类里的关联属性应该是集合类型(比如List<ProductComment>),而不是单个ProductComment对象。如果定义为单个对象,没有评论的Product会导致item.ProductComment为null,触发空引用。
  2. 视图逻辑不匹配关联关系:即使关联属性是集合,你直接访问item.ProductComment.CommentID的逻辑也不成立——一个Product对应多个评论,你需要遍历每个Product的评论集合,而不是直接访问单个评论。

具体解决方案

1. 修正Product实体类的关联属性

确保Product类里的关联属性是集合类型,并且提前初始化避免null:

public class Product
{
    // 你的其他Product属性(比如ProductID等)
    public int ProductID { get; set; }

    // 一对多关联:一个Product对应多个ProductComment
    public List<ProductComment> ProductComments { get; set; } = new List<ProductComment>();
}

2. 修正数据访问层的Include语句

确保Include的属性名和实体类里的集合属性名完全一致:

public class RepositoryProduct<T> : Repository<Product>, IRepositoryProduct<T> { 
    public RepositoryProduct(TradeTurkDBContext context) : base(context) { } 
    public List<Product> GetProductWithComment() { 
        // 这里改为ProductComments,匹配实体类的集合属性名
        return TradeTurkDBContext.Products.Include(x => x.ProductComments).ToList(); 
    } 
}

3. 调整Razor视图的逻辑

因为每个Product对应多个评论,你需要嵌套循环遍历评论集合,同时增加null判断避免空引用:

@foreach (var product in Model.ProductsC) { 
    @* 先判断当前产品是否有评论 *@
    @if (product.ProductComments != null && product.ProductComments.Any())
    {
        @* 遍历当前产品的所有评论 *@
        foreach (var comment in product.ProductComments)
        {
            <tr> 
                <td class="text-center"> 
                    <div class="dropdown custom-dropdown"> 
                        <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> 
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-more-horizontal"> 
                                <circle cx="12" cy="12" r="1"></circle> 
                                <circle cx="19" cy="12" r="1"></circle> 
                                <circle cx="5" cy="12" r="1"></circle> 
                            </svg> 
                        </a> 
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuLink1" style="will-change: transform;"> 
                            <a id="@comment.CommentID" class="dropdown-item" data-toggle="modal" data-target="#productCommentUpdate-@comment.CommentID">Güncelle</a> 
                            <a id="@comment.CommentID" class="dropdown-item" data-toggle="modal" data-target="#productCommentDelete-@comment.CommentID">Sil</a> 
                        </div> 
                    </div> 
                </td> 
                <td>@comment.CommentID</td> 
                <td>@comment.ShoppingUserID</td> 
                <td>@product.ProductID</td> 
                <td><button class="btn btn-outline-dark mb-2" data-toggle="modal" data-target="#productCommentView-@comment.CommentID">Yorumu Görüntüle</button></td> 
                <td>@comment.CreatedUserId</td> 
                <td>@comment.ModifiedUserId</td> 
                <td>@comment.CreatedUserType</td> 
                <td>@comment.ModifiedUserType</td> 
                <td>@comment.CreatedDate</td> 
                <td>@comment.ModifiedDate</td> 
                <td>@comment.ProductCommentIsActive</td> 
                <td>@comment.IsDeleted</td> 
            </tr> 
        }
    }
    else
    {
        <tr>
            <td colspan="13">Bu ürüne ait hiç yorum bulunmamaktadır.</td>
        </tr>
    }
}

4. 调试验证关联数据是否加载

在控制器代码里加个断点,查看ListProductComment中的每个Product对象的ProductComments集合是否有数据,确认Include语句确实生效加载了关联评论。

内容的提问来源于stack exchange,提问作者BerkGarip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:54:08