AutoMapper bidirectional mapping

前端 未结 4 1109
耶瑟儿~
耶瑟儿~ 2020-12-28 14:05

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

Mapper.CreateMap() and Mapper.CreateMap()?

相关标签:
4条回答
  • 2020-12-28 14:47

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

    0 讨论(0)
  • 2020-12-28 14:51

    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>();
        }
    }
    
    0 讨论(0)
  • 2020-12-28 14:54

    This is now baked into AutoMapper

    Mapper.CreateMap<SourceType, DestType>().ReverseMap();
    
    0 讨论(0)
  • 2020-12-28 14:55

    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();
    
    0 讨论(0)
提交回复
热议问题