Home > OS >  Why can't I add item into User Entity list?
Why can't I add item into User Entity list?

Time:11-24

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;
     }

CodePudding user response:

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();
  • Related