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

无法显示类别名称而非ID,遇NullReferenceException异常求助

问题原因

报错NullReferenceException是因为product.Category为null——加载产品数据时,没有同时加载关联的Category实体,导致无法访问Category.Name属性。

解决方案

1. 修复数据查询逻辑(根本解决)

修改B_Product.ProductList()方法,在EF Core查询中使用Include显式加载关联的Category实体:

using EntitiesApp;
using Microsoft.EntityFrameworkCore;

public static class B_Product
{
    public static List<ProductsEntity> ProductList()
    {
        using var dbContext = new YourDbContext(); // 替换为你的实际DbContext
        return dbContext.Products
            .Include(p => p.Category) // 显式加载关联的Category实体
            .ToList();
    }
}

2. 可选:启用懒加载(适合特定场景)

如果需要懒加载关联实体,可做以下调整:

  • 在ProductsEntity中将导航属性标记为virtual:
public virtual CategoriesEntity Category { get; set; }
  • 在你的DbContext配置中启用懒加载代理:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseLazyLoadingProxies()
                  .UseSqlServer("你的数据库连接字符串"); // 替换为实际数据库连接方式
}

注意:懒加载可能带来性能开销,列表展示场景建议优先使用Include显式加载。

3. 前端临时容错(避免页面崩溃)

如果暂时无法修改数据层,可在前端代码中添加空值判断:

<td>@(product.Category?.Name ?? "无分类")</td>

额外检查

确认数据库中所有Products的CategoryId都对应Categories表中存在的记录,若存在无效的CategoryId,也会导致product.Category为null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:27:21