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; }
}
2
Answers
The issue is
u.Products
is a list ofProduct
entities. So you cannot addProductDto
to it. Therefore you need change your code like this. create a newProduct
entity and set values based on the values in theProductDto
.So here
You need
var product = new Product
notnew ProductDto