AutoMapper bidirectional mapping

2020-02-20 07:21发布

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

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

4条回答
在下西门庆
2楼-- · 2020-02-20 07:46

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楼-- · 2020-02-20 07:55

This is now baked into AutoMapper

Mapper.CreateMap<SourceType, DestType>().ReverseMap();
查看更多
Rolldiameter
4楼-- · 2020-02-20 07:55

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>();
    }
}
查看更多
Explosion°爆炸
5楼-- · 2020-02-20 08:03

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

查看更多
登录 后发表回答