Terry
Terry

Reputation: 41

AutoMapper Resolve a property value on the destination based on the property value of a third object

Is it possible to use AutoMapper to map from Source to Destination conditionally resolving some properties based on the property value of another object? For example, mapping Source.Property to Destination.Property where ThirdObject.CountryCode.Equals("SomeCountry").

The current code base is setup so that values are being mapped from a DataReader to a list of objects. Then, if the ThirdObject.CountryCode has a certain value, then an amount property on the destination object must be multiplied by a multiplier.

Currently, I'm thinking of solving the problem by coming up with something like:

   Mapper.Map<IDataReader, Destination>(dataReader)
      .OnCondition(ThirdObject.CountryCode.Equals("SomeCountry")
      .ForMember(destination => destination.Amount)
      .UpdateUsing(new Multiplier(fixedAmount));

I'm hoping there is an easier way before going down that path.

Upvotes: 4

Views: 3104

Answers (1)

ozczecho
ozczecho

Reputation: 8849

Look at ResolveUsing:

    Mapper.CreateMap<Journal_Table, Journal>()
        .ForMember(dto => dto.Id, opt => opt.MapFrom(src => src.JournalId)) 
        .ForMember(dto => dto.Level, opt => opt.ResolveUsing<JournalLevelResolver>().FromMember(name => name.Journal_level));

Then:

public class JournalLevelResolver : ValueResolver<string, JournalLevel>
{

    protected override JournalLevel ResolveCore(string level)
    {
       ...

Upvotes: 3

Related Questions