我有以下内容:
class Product
{
int Id;
string Name;
}
class ProductDTO
{
int Id;
string Val;
}
class LookupDTO
{
string Name;
IEnumerable<ProductDTO> options;
}
我有Product
的列表,我需要将其映射到LookupDTO
Name = "myList"
和options = myProducts
var myProducts = new List<Product>();
myProducts (new Product { Id = 1, Name = "Apple" });
myProducts (new Product { Id = 2, Name = "Banana" });
myProducts (new Product { Id = 3, Name = "Pear" });
我想将其映射到LookupDTO
以生成以下内容:
LookupDTO
Name: "myList"
options: [ { id:1, val:"1 - Apple" }, { id:2, val:"2 - Banana" }, { id:3, val:"3 - Pear" } }
如何将我拥有的内容映射到此表单?
答案 0 :(得分:0)
我会将其拆分,而不是在一张超级地图中进行。
首先,在Product
和ProductDTO
之间添加映射器配置:
var config = new MapperConfiguration(cfg =>
{
// whatever other configurations you may have
cfg.CreateMap<Product, ProductDTO>().ForMember(
product => product.Val,
opts => opts.MapFrom(dto => dto.Name));
});
然后,使用映射器映射该属性:
var result = new LookupDTO()
{
Name = "myList",
options = mapper.Map<IEnumerable<ProductDTO>>(myProducts)
};