If I want to do bi-directional mapping, do I need to create two mapping?
Mapper.CreateMap<A, B>() and Mapper.CreateMap<B, A>()
?
If I want to do bi-directional mapping, do I need to create two mapping?
Mapper.CreateMap<A, B>() and Mapper.CreateMap<B, A>()
?
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).
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();
This is now baked into AutoMapper
Mapper.CreateMap<SourceType, DestType>().ReverseMap();
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 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).
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>();
}
}
© 2022 - 2024 — McMap. All rights reserved.