Automapper - map all properties except the one that does not exist in destination

2.8k views Asked by At

Using Automapper 3 (upgrading is not an option), I am wondering how can I map an entity (src) to destination where the property in destination does NOT exist in source?

Let's call the property in the destination some non mapped "temp" or "calculation" property. Of course when mapping, AM fails because the property in destination was not found in source.

CreateMap<SystemConfiguration, SystemConfigurationModel>()
                .ForMember(dest => dest.UserRulesModel, opt => opt.MapFrom(src => src.UserRules));

In the "UserRulesModel", I have this temp property. I want AM to ignore it when mapping from the entity (DB) into the View Model (UserRulesModel)

UPDATE: UserRulesModel is a collection, as is UserRules.

thank you.

1

There are 1 answers

2
OJ Raqueño On

You can configure that when you create the map from UserRules to UserRulesModel:

CreateMap<UserRules, UserRulesModel>()
    .ForMember(dest => dest.Temp, opt => opt.Ignore());

UPDATE

Let's say UserRules is a collection of UserRuleItem objects and UserRulesModel is a collection of UserRuleModelItem objects.

If there is a property in UserRuleModelItem that is not present in UserRuleItem, you can configure AutoMapper to ignore that property using the syntax I posted originally:

CreateMap<UserRuleItem, UserRuleModelItem>()
    .ForMember(dest => dest.Temp, opt => opt.Ignore());

The type of dest will be the type of object you are mapping to, which is UserRuleModelItem in this case.