Home > other >  How to use automapper in one to many relationship?
How to use automapper in one to many relationship?

Time:12-30

I have a method that creates a Product. Im getting such a user and checking if he is not null. If there is a user I'm creating new Product. I want to create Product, transfer this product to product dto and add this to the User Product List and return new ProductDto array within product name, product price and the name and Id of the user who created it. But when I try to add the product I'm getting error that I can't convert productDto to product. What I am doing wrong? Any suggestions?

public async Task<ActionResult<ProductDto>> AddProduct(string username, ProductDto productDto)
    {
        User user= await _context.Users
            .Where(x=>x.UserName==username)
            .Include(x => x.Products)
            .SingleOrDefaultAsync();
        
        if(user!= null)
        {
            var product = new Product
            {
                Name = productDto.Name,
                Price = productDto.Price,
                UserId = u.Id
            };

            var productToReturn = _mapper.Map<Product, ProductDto>(product);

           user.Products.Add(productToReturn); // Cannot convert productDto to product
           await _context.SaveChangesAsync();
        }
return Ok(productToReturn);



public class ProductDto
{
    public string Name { get; set; }
    public string Username { get; set; }
    public decimal Price { 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 User : BaseEntity
{
    public string UserName { get; set; }
    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }
    public List<Product> Products { get; set; }
}

I also configured automapper profiles

public AutoMapperProfiles()
    {
        CreateMap<Product, ProductDto>().ForMember(dest => dest.Username, opt => 
opt.MapFrom(src => src.User.UserName));
    }

CodePudding user response:

Seems the issue could be, you are trying to add ProductDto to the user.Products list. But it's looking for an object Product. try to modify code as,

if(user!= null)
{
    var product = new Product
    {
        Name = productDto.Name,
        Price = productDto.Price,
        UserId = u.Id
    };

    user.Products.Add(product);
    await _context.SaveChangesAsync();

    var productToReturn = _mapper.Map<Product, ProductDto>(product);
    return Ok(productToReturn);
}
  • Related