ASP.NET Core中如何通过购物车表的ProductId显示商品详情?
问题解决:购物车关联商品详情时的NullReferenceException
核心原因
你遇到的NullReferenceException是因为Entity Framework未加载Cart关联的Product实体,导致item.product为null。另外注意你的Product实体中没有定义Price字段,视图里的@item.product.Price会引发额外错误,需要同步修正。
解决方案
1. 显式加载关联实体(推荐)
修改GetCart方法,使用Include强制加载关联的Product,避免懒加载带来的潜在问题:
using Microsoft.EntityFrameworkCore; // 需引入此命名空间 public List<Cart> GetCart(int id) { var data = _context.Carts .Include(c => c.product) // 加载关联的Product实体 .Where(c => c.AccountId == id) .ToList(); return data; }
2. 配置懒加载(可选)
若偏好使用懒加载,需满足两个条件:
- 关联属性
product已设为virtual(你的代码已满足) - 在DbContext中启用懒加载代理:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseLazyLoadingProxies() .UseSqlServer("你的数据库连接字符串"); }
注意:懒加载易引发N+1查询性能问题,建议优先使用显式
Include方式。
3. 修正视图字段错误
Product实体无Price属性,需将视图中的Price改为现有字段(如Stock),或在Product实体中补充Price定义:
@model List<Web.Data.Entities.Cart> @foreach (var item in Model) { <p class="h6">@item.product.Stock</p> <p class="h6">@item.product.Desc</p> }
额外优化建议
- 检查
Cart表中ProductId是否对应Product表的有效记录,避免无效关联导致null - 完善控制器的空值判断,处理未登录场景:
public IActionResult Index() { int? accountId = HttpContext.Session.GetInt32("AccountId"); if (accountId == null) { return RedirectToAction("Login", "Account"); // 跳转到登录页 } var data = _cart.GetCart(accountId.Value); return View(data); }
内容的提问来源于stack exchange,提问作者Duy
相关产品推荐
相关产品推荐

