具有子元素的Automapper映射元素,该子元素列表到同一目标

时间:2014-08-17 12:28:17

标签: automapper

我有以下结构(简化):

class Source {
    string test {get; set;}
    List<SubClass> items {get; set;}
}

class SubClass {
    string rating {get; set;}
    string otherrating {get; set;}
}

class Destination {
    string test {get; set;}
    sttring rating {get; set;}
    string otherrating {get; set;}
}

我需要像这样使用Automapper:

Source -> Destination (this will affect "test" property)

Source.Items[0] -> `Desination` (this will affect "rating" && "otherrating" property)

我想使用automapper来做这件事,因为我有比上例更多的字段

你能给我一些建议吗?我可以为Source创建地图(不含SubClass)。

Mapper.CreateMap<Source, Destination>().ReverseMap();
...
var src = GetSourceWithListsFromDB(); // returns object of class Source
...
var model = Mapper.Map<Source, Destination>(src); // this maps Source, but doesn't map Source.Items[0].rating

我尝试了以下映射:

   Mapper.CreateMap<Source, Destination>().ForMember(dest => dest, opt=>opt.MapFrom(src => src.items[0]))

但这会引发错误。

1 个答案:

答案 0 :(得分:1)

您需要为评级和其他字段指定映射

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.rating, opt => opt.MapFrom(s => s.items[0].rating))
    .ForMember(dest => dest.otherrating, opt => opt.MapFrom(s => s.items[0].otherrating));
Mapper.CreateMap<Destination, Source>()
            .ForMember(dest =>dest.items, opt => opt.MapFrom(s=> new List<SubClass> {new SubClass(){ rating = s.rating, otherrating = s.otherrating}}));