I have a following Entity and Dto structure
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ProductProviders> ProductProviders { get; set; } = new HashSet<ProductProviders>();
}
public class ProductProviders
{
public int Id { get; set; }
public int ProviderId { get; set; }
public int ProductId { get; set; }
public Provider Provider { get; set; }
public Product Product { get; set; }
}
public class Provider
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public ICollection<Product> Products { get; set; } = new HashSet<Product>();
}
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<ProductProvidersDto> Providers { get; set; }
}
public class ProductProvidersDto
{
public int Id { get; set; }
public int ProviderId { get; set; }
public int ProductId { get; set; }
public ProviderDto Provider { get; set; }
public ProductDto Product { get; set; }
}
public class ProviderDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<ProductDto> Products { get; set; }
}
Now when I am inserting an Product object into database, I would like for it to automatically insert corresponding records into ProductProviders table.
I have tried several sulutions from other posts here and some other sources, and last solution that I came up with was this-
CreateMap<ProductDto, Product>()
.ForMember(dest => dest.ProductProviders, opts => opts.MapFrom(r => r.Providers.Select(r => r.Provider.Id).ToList()));
But this is giving me back an error, saying that relation does not exist (but this is the closest one to success, I think).
To be clear:
- DB relations are correct
- All the necessary information is specified
Is there some way to fix this mapping, so that when I insert a Product into database, it also inserts records into ProductProviders table?