简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM