简体   繁体   中英

AutoMapper Bidirectional Property Mapping

Here is what I'm doing.

Mapper.CreateMap<AViewModel, AModel>()
    .ForMember(x => x.Foo, x => x.MapFrom(src => src.Bar))
     ...
    .IgnoreAllNonExisting()
    .ReverseMap()
    .ForMember(x => x.Bar, x => x.MapFrom(src => src.Foo))
     ...
    .IgnoreAllNonExisting();

But in my case, I have too many properties to match.

And it feels like it have duplicate lines, only changing the order of each property.

Is there a way to do this, but without "duplicate" lines?

eg

Map Foo to Bar and Bar to Foo ( Foo <=> Bar )

*AutoMapper version - 3.3.1

AutoMapper supports mapping by convention, so it would naturally match up Foo property in AViewModel to Foo property in AModel because they share the same name. Also, you only need to call.IgnoreAllNonEsisting() once.

A solution would be to match the data for Foo from AViewModel and Foo in AModel and the same for the Bar property so that you would only need to do the following:

Mapper.CreateMap<AViewModel, AModel>()
    .IgnoreAllNonExisting()
    .ReverseMap();

I recommend reading through the getting started documentation for AutoMapper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM