如何使用自动映射器使用类型转换器映射特定值?

时间:2021-05-27 13:44:49

标签: c# automapper

我有具有 50 个属性的源对象和目标对象。但是其中 3 个转换的操作时间很长。 我想使用类型转换器映射其中的 3 个,其他自动映射。

public class PointEntityConverter : ITypeConverter<A, B>
{
    public PointEntity Convert(A source, B destination, ResolutionContext context)
    {
        if (destination == null)
            destination = new B();

        destination.X = ConvertForX(source);
        destination.Y = ConvertForY(source);
        destination.Z = ConvertForZ(source);

        // other properties should map automatically.

        return destination;
    }

    .....
    .....
}

我可以使用 ITypeConverter 进行此操作吗?

1 个答案:

答案 0 :(得分:0)

通常,您将使用 TypeConverter 编写从类型 A 到类型 B 的自定义映射逻辑。您仍然可以使用 IMapper 来自动映射一些复杂的属性。但是在您的情况下,您想为某些属性编写自定义映射逻辑并将其余部分留给 AutoMapper,这是比类型转换器更适合 Value Resolvers 的用例。检查下面的示例。

public class XPropertyResolver : IValueResolver<A, B, string>
{
    public string Resolve(A a, B b, string destMember, ResolutionContext context)
    {
        //Logic Here
    }
}

要使用值解析器,请在配置中执行以下操作。这将使用自动映射器逻辑映射 A 中的所有 B 属性,除了将通过定义的 ValueResolver 映射的属性“X”。

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<A, B>()
                .ForMember(dest => dest.X, o => o.MapFrom<XPropertyResolver>());
        });