AutoMapper双向映射

Ben*_*nny 25 bidirectional automapper

如果我想进行双向映射,是否需要创建两个映射?

Mapper.CreateMap<A, B>() and Mapper.CreateMap<B, A>()

Eri*_*ser 55

是的,但如果您发现自己经常这样做:

public static class AutoMapperExtensions
{
    public static void Bidirectional<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
    {
        Mapper.CreateMap<TDestination, TSource>();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

Mapper.CreateMap<A, B>().Bidirectional();
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 21

是的,因为如果你改变某些属性的类型(例如DateTime - > string),它不是双向的(你需要指示Automapper如何转换字符串 - > DateTime).


ASG*_*ASG 21

现在已经将其添加到AutoMapper中

Mapper.CreateMap<SourceType, DestType>().ReverseMap();
Run Code Online (Sandbox Code Playgroud)


Pao*_*chi 7

好主意埃里克!我添加了一个返回值,因此反向映射也是可配置的.

public static class AutoMapperExtensions
{
    public static IMappingExpression<TDestination, TSource> Bidirectional<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
    {
        return Mapper.CreateMap<TDestination, TSource>();
    }
}
Run Code Online (Sandbox Code Playgroud)