简体   繁体   中英

Automapper: multiple destination values populated from single source value

My DTO (destination) has a bunch of boolean values.

For example:

HasThisOption
HasThatOption
HasSomeOtherOption

These values are populated by doing some computation on one of the fields of the model object (source). This computation is a little costly, so rather than doing the same computation for every field on the DTO, I would like to only run the computation once.

Simple solution is to just call a function from my controller.. ie.. PopulateFields(source, dest)

But I don't want to have calls to Ignore for every destination field in my mapper configuration.. because there are about 40 of them... and it just looks messy and really makes no damn sense to do so.

What does one generally do in this situation?

You could use an AfterMap when defining your mapping between the source and the destination type:

Mapper.CreateMap<Source, Dest>().AfterMap((source, dest) =>
{
    // do your custom computations and assignments here
});

If the boolean fields are not present in the source type they will be ignored anyway during the standard mapping and have their default values in the destination. The AfterMap method allows you to change them.

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