数据库已填充的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
相关产品推荐
相关产品推荐

