I have a problem with the logic of a user adding items to his ICollection. When I hit this endpoint Im getting Error: System.NullReferenceException: Object reference not set to an instance of an object. I'm getting particular user from a database first then I'm creating new Product Class instance then I'm adding it into user's ICollection and finally saving changes in Db. Is this correct way of thinking ? Or do I miss something ? I attach my code below. Any tips or help ?
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; }
}