Home > front end >  How to add productDto to user's product array?
How to add productDto to user's product array?

Time:12-29

so basically my idea is that every product added to the database should have its name, price and the name of the user who created it assigned to it. I'm getting user and checking if user exists in the database. If he is im creating new product which is productDto instance. and finally when I want to add new product to user's entity Product List I'm occuring a problem that say's "you cannot convert from ProductDto to Product entity". How to overcome this? Any tips?

public async Task < ActionResult < ProductDto[] >> AddProduct(string username,
  ProductDto productDto) {

  User u = await _context.Users
    .Where(x => x.UserName == username)
    .Include(x => x.Products)
    .SingleOrDefaultAsync();

  if (u != null) {
    var product = new ProductDto {
      Name = productDto.Name,
        Price = productDto.Price,
        Username = u.UserName
    };
    u.Products.Add(product); // Im getting problem here
    await _context.SaveChangesAsync();
  }
  return u.Products.ToArray();
}

Here are my entities:

public class User : BaseEntity
{
    public string UserName { get; set; }
    public List<Product> Products { get; set; }
}

public class Product : BaseEntity
{
    public string Name { get; set; }
    public decimal Price { get; set ;}
    public User User { get; set; }
    public int UserId { get; set; }
}

public class ProductDto
{
    public string Name { get; set; }
    public string Username { get; set; }
    public decimal Price { get; set; }
}

CodePudding user response:

The issue is u.Products is a list of Product entities. So you cannot add ProductDto to it. Therefore you need change your code like this. create a new Product entity and set values based on the values in the ProductDto.

var product = new Product
{
    Name = productDto.Name,
    Price = productDto.Price,
    User = u
};
u.Products.Add(product);

CodePudding user response:

So here

 var product = new ProductDto
           {
                Name = productDto.Name,
                Price = productDto.Price,
                Username = u.UserName
           };

You need var product = new Product not new ProductDto

  • Related