Automapper:如何映射嵌套对象?

时间:2015-12-14 15:56:04

标签: c# automapper

我正在努力使用Automapper语法。 我有一个PropertySurveys列表,每个包含1个属性。 我希望将集合上的每个项目映射到一个新的对象中,该对象组合了两个类。

所以我的代码看起来像;

            var propertySurveys = new List<PropertyToSurveyOutput >();
            foreach (var item in items)
            {
                Mapper.CreateMap<Property, PropertyToSurveyOutput >();
                var property = Mapper.Map<PropertyToSurvey>(item.Property);
                Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput >();
                property = Mapper.Map<PropertyToSurvey>(item);
                propertySurveys.Add(property);
            }

我的简化课程看起来像;

public class Property
{
    public string PropertyName { get; set; }
}

public class PropertySurvey
{
    public string PropertySurveyName { get; set; }
    public Property Property { get; set;}
}

public class PropertyToSurveyOutput
{
    public string PropertyName { get; set; }
    public string PropertySurveyName { get; set; }
}

因此,在PropertyToSurveyOutput对象中,设置了第一个映射PropertyName之后。然后在设置第二个映射PropertySurveyName之后,将PropertyName重写为null。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

首先,Automapper支持集合的映射。您不需要在循环中映射每个项目。

第二 - 每次需要映射单个对象时都不需要重新创建地图。将映射创建放到应用程序启动代码中(或在首次使用映射之前)。

最后 - 使用Automapper,您可以创建映射并定义如何为某些属性执行自定义映射:

Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>()
   .ForMember(pts => pts.PropertyName, opt => opt.MapFrom(ps => ps.Property.PropertyName));

用法:

var items = new List<PropertySurvey>
{
    new PropertySurvey { 
          PropertySurveyName = "Foo", 
          Property = new Property { PropertyName = "X" } },
    new PropertySurvey { 
          PropertySurveyName = "Bar", 
          Property = new Property { PropertyName = "Y" } }
};

var propertySurveys = Mapper.Map<List<PropertyToSurveyOutput>>(items);

结果:

[
  {
    "PropertyName": "X",
    "PropertySurveyName": "Foo"
  },
  {
    "PropertyName": "Y",
    "PropertySurveyName": "Bar"
  }
]

更新:如果您的Property类有许多属性,则可以定义两个默认映射 - 一个来自Property

Mapper.CreateMap<Property, PropertyToSurveyOutput>();

来自PropertySurvey的人。在使用PropertySurvey的映射后使用第一个映射:

Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>()
      .AfterMap((ps, pst) => Mapper.Map(ps.Property, pst));

答案 1 :(得分:1)

automapper属性名称的第一个规则应该是相同的,然后才会正确映射并分配值,但在您的情况下,一个属性名称只是“Property”而第二个属性名称是“PropertyName”所以make属性名称相同它将起作用为你

相关问题