如何使用自动映射器将对象属性数组映射为复杂类型的对象数组
我的类结构如下:
public class Product : Entity, IAggregateRoot
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<ProductPicture> ProductPictures { get; set; }
public virtual List<ProductSpecification> Specifications { get; set; }
}
public class ProductSpecification : Entity
{
public Guid ProductId { get; set; }
public Guid SpecificationId { get; set; }
public virtual Product Product { get; set; }
public virtual Specification Specification { get; set; }
public virtual List<ProductSpecificationData> Data { get; set; }
}
public class ProductSpecificationData : Entity
{
public Guid Id { get; set; }
public Guid ProductSpecificationId { get; set; }
public string Value { get; set; }
public virtual ProductSpecification ProductSpecification { get; set; }
}
public class Specification: Entity, IAggregateRoot
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<ProductSpecification> ProductSpecifications { get; set; }
}
我想将产品映射到ProductDetailDTO
public class ProductDetailDTO
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public class ProductSpecification
{
public string Name { get; set; } //from specification
public string Description { get; set; } //from specification
public class ProductSpecificationData
{
public string Value { get; set; }
}
public List<ProductSpecificationData> Data { get; set; } //from ProductSpecificationData
}
public List<ProductSpecification> Specifications { get; set; }
}
我总是在ProductDetailDTO-> ProductSpecification-> Data中获取数据。
我试图做这样的事情:
mc.CreateMap<Product, ProductDetailDTO>().ForMember(dest => dest.PictureUris, mo => { mo.MapFrom(src => src.ProductPictures.Select(pp => pp.PictureUri)); })
.ForMember(dest => dest.Specifications, mo => { mo.MapFrom(src => src.Specifications.Select(s => s.Specification)); });
mc.CreateMap<Specification, ProductDetailDTO.ProductSpecification>();
mc.CreateMap<ProductSpecificationData, ProductDetailDTO.ProductSpecification.ProductSpecificationData>();
地图调用的代码:
Product Product = new Product
{
Name = "test product",
Description = "test product description",
ProductPictures = new List<ProductPicture>
{
new ProductPicture { PictureUri = "test uri 1" },
new ProductPicture { PictureUri = "test uri 2" }
},
Specifications = new List<ProductSpecification>
{
new ProductSpecification {
Specification = new Specification
{
Name = "test specification 1",
Description = "test specification description 1",
},
Data = new List<ProductSpecificationData>
{
new ProductSpecificationData
{
Data1 = "test data1",
Data2 = "test data2",
}
}
},
}
};
ProductDetailDTO productDetail = mapper.Map<ProductDetailDTO>(Product);