1

so basically I would like to create a functionality where the user adds products to their product list and saves them to the database. I have User entity and Product Entity in one to many relationship. My plan was to get user and check if user is logged in ( if user is not null ) and if it is make him able to create a new product entity and add it to user's Product[] and save it in the database. The problem is that when I wants to add the created product to the list I'm getting ArgumentNullException. How to overcome this? Any tips ?

public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public Product[] Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public User User { get; set; }
    public int UserId { get; set; }
}

    [HttpPost("CreateAndAddProduct")]
    public async Task<ActionResult<Product[]>> AddProduct(string User)
    {
        ProductModel productModel=new ProductModel();

        User user= await _context.Users.Where(x=>x.UserName==User).FirstOrDefaultAsync();
        Product[] userList = u.Products;

        if(user!=null)
        {
           var product = new Product
           {
                Name = "gloves",
                UserId = user.Id
           };
           userList.Append(product); // here im getting ArgumentNullException
           await _context.SaveChangesAsync();
        }

        return userList;
     }
2
  • 1
    you are not pulling the navigation properties.... so u.Products is null Commented Nov 23, 2022 at 17:05
  • Add .Include(x => x.Products) before the .Where() on your query Commented Nov 23, 2022 at 17:12

1 Answer 1

1

Since this is a 1 to N relationship, you need to include the Products in the query, for EF make a join in the database.

 User user= await _context.Users
    .Where(x => x.UserName == User)
    .Include(x => x.Products)
    .FirstOrDefaultAsync();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.