[英]How to map from a flat entity to more than one DTO?
我希望在 C# .NET Core 中使用 AutoMapper 從已經扁平化的實體映射到一組嵌套的 DTO。 DTO 也有一對多的關系,扁平化的實體隱藏在結構中。 例如:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public int Weight { get; set; }
}
public class ProductDto
{
public string Name { get; set; }
public IEnumerable<PriceDto> Prices { get; set; }
}
public class PriceDto
{
public int Price { get; set; }
public int Weight { get; set; }
}
我知道 AutoMapper 提供的 ReverseMap() 函數,但是鑒於我從一個扁平化的實體開始,我不確定如何設置 ProductDto 和 PriceDto 之間的關系。
編輯:這是我以“產品”形式收到的扁平化數據的示例集。 注意 ProductDto 和 PriceDto 之間推斷出的一對多關系,這將是必需的。
+-----+-------+-------+--------+
| Id | Name | Price | Weight |
+-----+-------+-------+--------+
| 1 | "foo" | 8 | 12 |
| 2 | "foo" | 12 | 18 |
| 3 | "bar" | 3 | 1 |
| 4 | "bar" | 6 | 2 |
| ... | | | |
+-----+-------+-------+--------+
您需要實現自己的轉換器,如下所示:
ProductsConverter
public class ProductsConverter : ITypeConverter<List<Product>, List<ProductDto>> { public List<ProductDto> Convert(List<Product> source, List<ProductDto> destination, ResolutionContext context) { return source.GroupBy(p => p.Name) .Select(r => new ProductDto { Name = r.Key, Prices = source.Where(pp => pp.Name == r.Key) .Select(rr => new PriceDto { Price = rr.Price, Weight = rr.Weight }) }).ToList(); } }
ModelProfile
public class ModelProfile: Profile { public ModelProfile() { CreateMap<List<Product>, List<ProductDto>>() .ConvertUsing<ProductsConverter>(); } }
用例
public IActionResult Index() { List<Product> products= new List<Product>() { new Product{ Id = 1, Name = "foo", Price = 8, Weight = 12}, new Product{ Id = 2, Name = "foo", Price = 12, Weight = 18}, new Product{ Id = 3, Name = "bar", Price = 3, Weight = 1}, new Product{ Id = 4, Name = "bar", Price = 6, Weight = 2}, }; var result = _mapper.Map<List<ProductDto>>(products); return Ok(result); }
我會定義兩個域配置文件。 一種用於 Product 到 ProductDto
CreateMap<Product, ProductDto>()
.ForMember(x => x.Id , opts => opts.Ignore())
.ForMember(x => x.Price , opts => opts.Ignore())
.ForMember(x => x.Weight , opts => opts.Ignore())
.ForMember(x => x.Name , opts => opts.MapFrom(y => y.Name));
一個是 Product 到 PriceDto
CreateMap<Product, ProductDto>()
.ForMember(x => x.Id , opts => opts.Ignore())
.ForMember(x => x.Name , opts => opts.Ignore())
.ForMember(x => x.Price , opts => opts.MapFrom(y => y.Price ))
.ForMember(x => x.Weight , opts => opts.MapFrom(y => y.Weight ));
然后從同一源一次映射到兩個不同的目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.