我有一个扁平的对象列表,看起来像这样:
//SOURCE OBJECT
public class SourceObject
{
public string Code { get; set; }
public string Name { get; set; }
public string ImageUri1 { get; set; }
public string ImageUri2 { get; set; }
public string ImageUri3 { get; set; }
// etc...
}
//TARGET OBJECT
public class TargetObject
{
public string Code { get; set; }
public string Name { get; set; }
public List<TargetObjectImage> Images {get;set;}
}
public class TargetObjectImage
{
public string Name { get; set; }
public string ImageUri { get; set; }
}
我需要映射的一些性质SourceObject嵌套收集TargetObjectImage TargetObject导航属性。
实际上,我想把它命名为&;unpivot&;操作。此外,源数据结构并不总是必须存储所有的图像,在这种情况下ImageUri…属性将为空,不应添加到嵌套集合中。
public class SourceObjectProfile : Profile
{
public SourceObjectProfile()
{
var map = CreateMap<SourceObject, TargetObject>()
.ForMember(o => o.Name, o => o.MapFrom(m => m.Name))
.ForMember(o => o.Code, o => o.MapFrom(m => m.Code))
}
}
我正在使用AutoMapper。能给我点建议吗?
工作代码:
public class CustomResolver : IValueResolver<SourceObject, TargetObject, List<TargetObjectImage>>
{
public List<TargetObjectImage> Resolve(SourceObject source, TargetObject destination, List<TargetObjectImage> destMember, ResolutionContext context)
{
return new List<TargetObjectImage>
{
new TargetObjectImage
{
Uri = source.ImageUri1
},
new TargetObjectImage
{
Uri = source.ImageUri2
},
new TargetObjectImage
{
Uri = source.ImageUri3
},
};
}
}
public class SourceObjectProfile : Profile
{
public SourceObjectProfile()
{
var map = CreateMap<SourceObject, TargetObject>()
.ForMember(o => o.Name, o => o.MapFrom(m => m.Name))
.ForMember(o => o.Code, o => o.MapFrom(m => m.Code))
.ForMember(o => o.Images, o => o.MapFrom(new CustomResolver()));
}
}