向用户ICollection添加项时遇NullReferenceException问题求助
问题:向用户ICollection添加项时触发NullReferenceException错误
实现用户向其ICollection添加项的逻辑时,调用接口出现以下错误:System.NullReferenceException: Object reference not set to an instance of an object
我的思路是先从数据库获取指定用户,创建新的Product类实例,将其添加到用户的ICollection中,最后保存数据库更改。请问这个思路是否正确?我是否遗漏了什么?附上代码求指点:
public class ProductController : BaseController { private readonly DataContext _context; public ProductController(DataContext context) { _context = context; } [HttpPost("AddProduct")] public async Task<ActionResult<Product>> AddProduct(AddProductModel addProductModel) { if(!await UserExist(addProductModel.User.UserName)) return BadRequest("Something gone wrong, there is no such a user"); var product = new Product { Name = addProductModel.productDto.Name }; addProductModel.User.Products.Add(product); await _context.SaveChangesAsync(); return product; } private async Task<bool> UserExist(string username) { return await _context.Users.AnyAsync(x => x.UserName == username); } } public class AddProductModel { public User User { get; set; } public ProductDto productDto { get; set; } }
问题分析与修正方案
你的思路方向正确,但代码存在三个关键问题导致空引用:
addProductModel.User为空:接口接收的AddProductModel中,前端不会传入完整的User实体,仅传入用户名时addProductModel.User为null,调用其属性时直接触发异常。- 未加载数据库中的实际User实例:
UserExist仅验证用户存在,但未从数据库取出User实体,你操作的addProductModel.User不是EF追踪的对象,无法正确关联到数据库。 Products集合未初始化:如果User类的Products属性未在构造函数中初始化为List<Product>,即使User实例有效,调用Add方法时也会因集合为null报错。
修正后的代码
- 修改
AddProduct方法,从数据库加载User实体并关联Product:
[HttpPost("AddProduct")] public async Task<ActionResult<Product>> AddProduct(AddProductModel addProductModel) { // 从数据库加载用户,显式加载Products集合 var user = await _context.Users .Include(u => u.Products) .FirstOrDefaultAsync(x => x.UserName == addProductModel.UserName); if (user == null) return BadRequest("不存在该用户"); var product = new Product { Name = addProductModel.productDto.Name, UserId = user.Id // 假设Product存在UserId外键属性 }; user.Products.Add(product); await _context.SaveChangesAsync(); return product; }
- 优化
AddProductModel,仅传递用户名而非完整User对象:
public class AddProductModel { public string UserName { get; set; } public ProductDto productDto { get; set; } }
- 确保User类中初始化
Products集合:
public class User { // 其他属性... public ICollection<Product> Products { get; set; } = new List<Product>(); }
这样修改后,既避免了空引用问题,又保证EF能正确追踪实体变更并保存到数据库。
内容的提问来源于stack exchange,提问作者Szymon0202020
相关产品推荐
相关产品推荐

