我正在努力使用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);
}
Run Code Online (Sandbox Code Playgroud)
我的简化课程看起来像;
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; }
}
Run Code Online (Sandbox Code Playgroud)
因此,在PropertyToSurveyOutput对象中,在设置第一个映射PropertyName之后.然后在设置第二个映射PropertySurveyName之后,将PropertyName重写为null.我该如何解决?
首先,Automapper支持集合的映射.您不需要在循环中映射每个项目.
其次 - 每次需要映射单个对象时,无需重新创建映射.将映射创建放到应用程序启动代码中(或在首次使用映射之前).
最后 - 使用Automapper,您可以创建映射并定义如何为某些属性执行自定义映射:
Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>()
.ForMember(pts => pts.PropertyName, opt => opt.MapFrom(ps => ps.Property.PropertyName));
Run Code Online (Sandbox Code Playgroud)
用法:
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);
Run Code Online (Sandbox Code Playgroud)
结果:
[
{
"PropertyName": "X",
"PropertySurveyName": "Foo"
},
{
"PropertyName": "Y",
"PropertySurveyName": "Bar"
}
]
Run Code Online (Sandbox Code Playgroud)
更新:如果您的Property类有许多属性,您可以定义两个默认映射 - 一个来自Property:
Mapper.CreateMap<Property, PropertyToSurveyOutput>();
Run Code Online (Sandbox Code Playgroud)
一个来自PropertySurvey.使用映射后使用第一个映射PropertySurvey:
Mapper.CreateMap<PropertySurvey, PropertyToSurveyOutput>()
.AfterMap((ps, pst) => Mapper.Map(ps.Property, pst));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10073 次 |
| 最近记录: |