我有一个简单的数据模型:
// Model
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
.... Another values here ....
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
.... Another values here ....
}
// ViewModel
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}我希望(使用 AutoMapper )将PersonViewModel的值映射到相应的属性(AutoMapper发现属性应该位于根对象还是子对象中)。记住,AutoMapper不应该创建Person对象或Address (在自动映射之前,必须手动创建对象以填充另一个属性),AutoMapper使用已经存在的对象。例如:
var addressObj = new Address
{
... Filling some values...
};
var personObj = new Person
{
Address = addressObj;
... Filling some values...
};
mapper.Map(personViewModelObj, personObj); // How to make this work for both Person and Address properties?如何使自动映射同时适用于person属性和address属性?
我应该添加两个映射规则(地址和人员),并执行两次mapper.Map()吗?
发布于 2018-04-25 18:16:02
使用@Jasen评论,我让它起作用了。主要的问题是我正在向相反的方向映射。正式文件中的这句话解决了这个问题:
不平展只为
ReverseMap配置。如果需要展开,则必须配置Entity->Dto,然后调用ReverseMap从Dto->Entity创建不平坦类型的映射配置。
以下是链接:
https://github.com/AutoMapper/AutoMapper/blob/master/docs/Reverse-Mapping-and-Unflattening.md
换句话说,为了不讨好地工作,我必须(或必须)在这个方向上绘制地图:
CreateMap<HierarchicalObject, FlattenedObject>()
.ReverseMap();https://stackoverflow.com/questions/50011840
复制相似问题