27

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

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

Benny
  • 8,547
  • 9
  • 60
  • 93

4 Answers4

56

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();
Eric Hauser
  • 5,551
  • 3
  • 26
  • 29
  • while this may not answer the question, it certainly solves the underlying problem posed – hanzolo Feb 24 '15 at 19:12
  • Deprecated in 4.2, Removed in 5 :( https://stackoverflow.com/questions/38194012/automapper-mapper-does-not-contain-definition-for-createmap – Jim Elrod Jun 04 '17 at 02:11
28

This is now baked into AutoMapper

Mapper.CreateMap<SourceType, DestType>().ReverseMap();
ASG
  • 957
  • 9
  • 20
  • 1
    This does not work with custom mappings, only when the property names are the same in both classes. – Michael Brown Feb 05 '16 at 21:35
  • @MichaelBrown even then, `ReverseMap` called on `IMappingExpression` returns an `IMappingExpression`, so the reverse custom mapping can then be defined. I move this be the new accepted answer. – Bondolin Feb 27 '20 at 17:48
21

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

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Makes sense, but it would be nice it the library TRIED to do the mapping as a convention, and you could explicitly disable it if it wasn't working. For example, I map domain objects to view models and bidirectional mapping would work perfectly for me. – John B Jan 17 '12 at 17:26
7

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>();
    }
}
Paolo Sanchi
  • 783
  • 9
  • 19