AutoMapper bidirectional mapping

强颜欢笑 提交于 2019-11-29 00:05:50

问题


If I want to do bi-directional mapping, do I need to create two mapping?

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


回答1:


Yes, because if you change the type of some property (for example DateTime -> string) it is not bidirectional (you will need to instruct Automapper how to convert string -> DateTime).




回答2:


Yes, but if you find yourself doing this often:

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

then:

Mapper.CreateMap<A, B>().Bidirectional();



回答3:


This is now baked into AutoMapper

Mapper.CreateMap<SourceType, DestType>().ReverseMap();



回答4:


Great idea Eric! I've added a return value, so the reverse mapping is configurable too.

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


来源:https://stackoverflow.com/questions/2439024/automapper-bidirectional-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!