Automapper:如何映射嵌套对象?

Automapper: how to map nested object?

我正在为 Automapper 语法苦苦挣扎。 我有一个 属性 调查列表,每个调查包含 1 属性。 我希望将集合中的每个项目映射到一个新对象中,该对象结合了 2 类.

所以我的代码看起来像;

            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; }
}

所以在属性ToSurveyOutput 对象中,在第一个映射属性Name 设置之后。然后在设置第二个映射后 属性SurveyName,但 属性Name 被覆盖为 null。 我该如何解决这个问题?

首先,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 class 有很多属性,您可以定义两个默认映射 - 一个来自 Property:

Mapper.CreateMap<Property, PropertyToSurveyOutput>();

还有一个来自 PropertySurvey。并在使用来自 PropertySurvey:

的映射后使用第一个映射
Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>()
      .AfterMap((ps, pst) => Mapper.Map(ps.Property, pst));

automapper 属性 名称的第一条规则应该相同,只有它才能正确映射并分配值,但在您的情况下,一个 属性 名称仅为 "Property",第二个 属性 名字是 "PropertyName" 所以让 属性 名字相同它会为你工作