Automapper - 在两个 类 之间创建一个简单的映射,并为特定类型使用自定义转换器

Automapper - Create a simple mapping between two classes AND use custom converters for specific types

我想用 Automapper 映射两个 类,但我想在目标 特定 属性 类型 中使用自定义转换器,不是特定成员

简单示例:

public class Source
{
    public string SomeString {get;set;}  = "TEST";

    public string SomeNullableInt {get;set;}  = "10";

    public string AnotherNullableInt {get;set;}  = "This is not an integer";

    public string SomeDate {get;set;}  = "20220202";
}
public class Destination
{
    public string SomeString {get;set;};

    public int? SomeNullableInt {get;set;};

    public int? AnotherNullableInt {get;set;};

    public DateTime SomeDate {get;set;};
}
public class NullableIntTypeConverter : ITypeConverter<string, int?>
{
    public int? Convert(string source, int? destination, ResolutionContext context)
    {
        // return My Custom Logic here.
    }
}
public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
{
    public DateTime Convert(string source, DateTime destination, ResolutionContext context)
    {
        // return My Custom Logic here.
    }
}
var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>());
// Dear Automapper, please use my custom ITypeConverters, whenever I map Source and Destination....(I tried for hours on this one, but I failed)

我的问题:我如何告诉 Automapper 始终 使用我的自定义 ITypeConverters for ANY 诠释?和目标中的日期时间,每当我映射源和目标时? (不使用“成员映射”......)

谢谢!

您使用 ConvertUsing() 指定要用于将一种类型映射到另一种类型的转换器。请参阅 Custom Type Converters 中的示例:

var configuration = new MapperConfiguration(cfg => {
  cfg.CreateMap<string, int>().ConvertUsing(s => Convert.ToInt32(s));
  cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
  cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
  cfg.CreateMap<Source, Destination>();
});

在您的情况下,您可以按如下方式注册转换器:

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<Source, Destination>();
    cfg.CreateMap<string, int?>().ConvertUsing<NullableIntTypeConverter>();
    cfg.CreateMap<string, DateTime>().ConvertUsing<DateTimeTypeConverter>();
});