[英]Automapper many - to - many relationship
I have a following Entity and Dto structure我有以下实体和 Dto 结构
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.现在,当我将Product
object 插入数据库时,我希望它自动将相应的记录插入ProductProviders
表中。
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:要清楚:
Is there some way to fix this mapping, so that when I insert a Product
into database, it also inserts records into ProductProviders
table?有没有办法修复这个映射,这样当我将Product
插入数据库时,它也会将记录插入到ProductProviders
表中?
You can use AfterMap
(see: https://docs.automapper.org/en/stable/Before-and-after-map-actions.html ) and write there logic to assign/fill needed fields in your own way:您可以使用AfterMap
(请参阅: https://docs.automapper.org/en/stable/Before-and-after-map-actions.html )并在那里编写逻辑以您自己的方式分配/填充所需的字段:
.AfterMap((src, dest) =>
{
// write custom assignment logic etc.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.