Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add productDto to user's product array?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading