c# - Automapper 帮助映射复杂的 c# 对象

标签 c# automapper

我正在尝试使用 AutomapperVehicle 对象映射到 Motor 对象

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 进行简单映射。

最佳答案

这对我有用:

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);

关于c# - Automapper 帮助映射复杂的 c# 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950232/

相关文章:

c# - 空接口(interface)代码有味道吗?

c# - 在 C# 中实现 SSL 隧道

c# - 如果两个条件之一为真,则结束协程

c# - Automapper 使用自定义映射展平多个复杂对象

c# - 使用 Automapper 的自定义映射,其中目标字段是源中两个字段的串联

c# - 在 ASP.NET Core 1.0 MVC6 中使用内置 IoC 配置 AutoMapper 4.2

c# - 使用 AutoMapper 将空字符串替换为空值

c# - AutoMapper map 子属性也定义了 map

c# - ASP.NET Core Web API - 执行 'LastOrDefault' 操作的查询必须具有确定性排序顺序

c# - 如何制作 Optional 1 :1 Relationship in EF6 with the same Entity Type on both sides?