AutoMapper bidirectional mapping
Asked Answered
S

4

28

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

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

Stringent answered 13/3, 2010 at 16:17 Comment(0)
H
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).

Hine answered 13/3, 2010 at 16:21 Comment(1)
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.Ebracteate
D
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();
Dorladorlisa answered 24/10, 2010 at 18:44 Comment(2)
while this may not answer the question, it certainly solves the underlying problem posedAnastomosis
Deprecated in 4.2, Removed in 5 :( #38194512Photomural
L
28

This is now baked into AutoMapper

Mapper.CreateMap<SourceType, DestType>().ReverseMap();
Lezlie answered 30/1, 2015 at 14:31 Comment(2)
This does not work with custom mappings, only when the property names are the same in both classes.Gerri
@MichaelBrown even then, ReverseMap called on IMappingExpression<SourceType, DestType> returns an IMappingExpression<DestType, SourceType>, so the reverse custom mapping can then be defined. I move this be the new accepted answer.Syncarpous
H
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).

Hine answered 13/3, 2010 at 16:21 Comment(1)
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.Ebracteate
A
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>();
    }
}
Abyss answered 4/1, 2013 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.