考慮下面的實體模型:爲什麼在這裏需要自定義解析器(AutoMapper)?
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根據viewmodel中的命名約定構造一個新的座標值對象?
更新
要回答第一個評論,並沒有什麼特別之處實體視圖模型映射:
CreateMap<Location, LocationModel>();
您可以包括從實體模型的映射? – 2012-02-03 17:31:38
我已經包含了從實體到模型的映射。 – danludwig 2012-02-03 19:01:25