给定以下实体模型:
public class Location
{
public int Id { get; set; }
public Coordinates Center { get; set; }
}
public class Coordinates
{
public double? Latitude { get; set; }
public double? Longitude { get; set; }
}
...以及以下视图模型:
public class LocationModel
{
public int Id { get; set; }
public double? CenterLatitude { get; set; }
public double? CenterLongitude { get; set; }
}
LocationModel 属性的命名使得从实体到模型的映射不需要自定义解析器。
但是,当从模型映射到实体时,需要以下自定义解析器:
CreateMap<LocationModel, Location>()
.ForMember(target => target.Center, opt => opt
.ResolveUsing(source => new Coordinates
{
Latitude = source.CenterLatitude,
Longitude = source.CenterLongitude
}))
为什么是这样?有没有更简单的方法让 AutoMapper 根据视图模型中的命名约定构造一个新的坐标值对象?
更新
要回答第一条评论,实体到视图模型的映射没有什么特别之处:
CreateMap<Location, LocationModel>();