简体   繁体   中英

AutoMapper Conditional Mapping based on source and destination

I need to map a UpdateViewModel to its Model . The Model is

public class Model
{
    // ...
    public DateTime? Disabled
}

The UpdateViewModel is

public class UpdateViewModel
{
    // ...
    Status Status
}
public enum Status
{
    Disabled,
    Active
}

I now have this code

if(uvm.Status == Status.Active)
{
    model.Disabled = null;
}
else
{
    if(model.Disabled == null)
    {
        model.Disabled = DateTime.UtcNow;
    }
}

I want to get this in my Map but i struggle to have an if/else condition and I struggle to set Disabled to null .

It should cover the following cases:

Model.Disabled == null and uvm.Status == Status.Disabled -> Set model.Disabled to DateTime.UtcNow

Model.Disabled == null and uvm.Status == Status.Active -> Stay with model.Disabled = null

Model.Disabled != null and uvm.Status == Status.Disabled -> Stay with current model.Disabled

Model.Disabled != null and uvm.Status == Status.Active -> Set model.Disabled to null

I managed to get this working with an IValueResolver

public class DisabledResolver : IValueResolver<UpdateViewModel, Model, DateTime?>
{
    public DateTime? Resolve(UpdateViewModel uvm, Model entity, DateTime? value, ResolutionContext context)
    {
        if(uvm.Status == Status.Active)
        {
            return null;
        }
        else
        {
            if(entity.Disabled == null)
            {
                return DateTime.UtcNow;
            }
            return entity.Disabled;
        }
    }
}

and

CreateMap<UpdateViewModel, Model>()
    .ForMember(model => model.Disabled, opt => opt.MapFrom<DisabledResolver>());

You can create custom configuration rules for mapping between types. For example,

 var configuration = new MapperConfiguration(cfg => {
                cfg.CreateMap<UpdateViewModel, Model>()
                  .ForMember(dest => dest.Disabled, opt => opt.MapFrom((src,dest)=>
                  {
                      return src.Status switch
                      {
                          Status.Active => null,
                          Status.Disabled when dest.Disabled is null => DateTime.UtcNow,
                          Status.Disabled => dest.Disabled,
                          _ => throw new ArgumentException()
                      };

                  }));
            });


and then

var mapper = new Mapper(configuration);
var result = mapper.Map<UpdateViewModel,Model>(uModel,model);

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