我正在尝试使用Vehicle
将Motor
对象映射到Automapper
对象
public class Range<T>
{
public T Min { get; set; }
public T Max { get; set; }
}
public Enum SpeedType
{
[Display(Name = "-")] Unknown = 0,
[Display(Name = "M")] Manual= 1,
[Display(Name = "A")] Automatic= 2
}
public class Vehicle
{
public Range<string> Speed { get; set; }
}
public class Motor
{
public Range<SpeedType?> Speed { get; set; }
}
我尝试使用MapFrom
(阅读文档)没有成功。有人可以指出我正确的方向。我什至不确定是否可以使用Automapper
来映射它。过去,我曾使用automapper进行简单的映射。
答案 0 :(得分:2)
这对我有用:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<string, SpeedType?>().ConvertUsing(speed =>
{
switch (speed)
{
case "M": return SpeedType.Manual;
case "A": return SpeedType.Automatic;
default: return SpeedType.Unknown;
}
});
cfg.CreateMap<Range<string>, Range<SpeedType?>>();
cfg.CreateMap<Vehicle, Motor>();
});
var vehicle = new Vehicle
{
Speed = new Range<string>
{
Min = "M",
Max = "A"
}
};
var motor = Mapper.Map<Vehicle, Motor>(vehicle);
答案 1 :(得分:0)
我想出了以下映射来解决我的问题。我写了一个GetEnum自定义方法
CreateMap<Vehicle,Motor>()
.ForMember(g => g.Speed, opt => opt.MapFrom(u=> new Range<SpeedType?>
{
Min = EnumHelper.GetEnum<SpeedType?>(u.Speed.Min),
Max = EnumHelper.GetEnum<SpeedType?>(u.Speed.Max),
}))