0

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; }
}
  • How are you injecting `DataContext context`? – Luke Garrigan Jul 11 '22 at 18:34
  • You may want to re-read the [What is NRE](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) as well [mre] guidance on posting code and [edit] the question with information. – Alexei Levenkov Jul 11 '22 at 18:34
  • Most likely `addProductModel` is null. If I were a betting man, I'd say you are sending it as json and need to add the `[FromBody]` attribute to the parameter. – Jonesopolis Jul 11 '22 at 18:35

1 Answers1

0

Adding this line of code will solve your current problem:addProductModel.User.Products = new List<Product>();

Below is my test code:

Controller:

[HttpPost]
public async Task<ActionResult<Product>> AddProduct(AddProductModel addProductModel)
{
    var product = new Product
    {
        Name = addProductModel.productDto.Name
    };
    //Add this line
    addProductModel.User.Products = new List<Product>();

    addProductModel.User.Products.Add(product);
    await _context.SaveChangesAsync();
    return product;
}

Test Result: enter image description here enter image description here

Chen
  • 4,499
  • 1
  • 2
  • 9