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

数据库已填充的Product Category外键字段为何在代码中显示为null?

问题与解决:EF中数据库已填充的外键字段在代码中显示为null

问题现象

  • ProductCategories字段为null,引发报错:Object reference not set to the instance of an object
  • 数据库中该外键字段已填充(对应数据库截图显示字段有值)
  • 调试模式下单步执行时页面可正常渲染,但调用Product类型分页列表myProducts时会出错

解决方法

原因是在EF Core的IQueryable查询中,未通过Include方法显式加载关联的ProductCategory实体。添加.Include(pc => pc.ProductCategory)后问题解决。

修改后的完整查询代码如下:

IQueryable<Product> ProductIQ = from p in Context.Product
                                    .Include(pc => pc.ProductCategory)
                                    select p;

if (!String.IsNullOrEmpty(searchString))
{
    ProductIQ = ProductIQ.Where(p => p.ProductName.Contains(searchString));
}

switch (sortOrder)
{
    case "name_desc":
        ProductIQ = ProductIQ.OrderByDescending(p => p.ProductName)
            .ThenByDescending(p => p.Wholesaler).ThenByDescending(p => p.ProductDescr1);
        break;
    default:
        ProductIQ = ProductIQ.OrderBy(p => p.ProductName)
            .ThenByDescending(p => p.Wholesaler).ThenByDescending(p => p.ProductDescr1);
        break;
}

var pageSize = Configuration.GetValue("PageSize", 10);

myProducts = await PaginatedList<Product>.CreateAsync(
    ProductIQ.AsNoTracking(), pageIndex ?? 1, pageSize);

return Page();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:01:08