Automapper: Ignore on condition of

心已入冬 提交于 2019-12-17 07:52:07

问题


Is it possible to ignore mapping a member depending on the value of a source property?

For example if we have:

public class Car
{
    public int Id { get; set; }
    public string Code { get; set; }
}

public class CarViewModel
{
    public int Id { get; set; }
    public string Code { get; set; }
}

I'm looking for something like

Mapper.CreateMap<CarViewModel, Car>()
      .ForMember(dest => dest.Code, 
      opt => opt.Ignore().If(source => source.Id == 0))

So far the only solution I have is too use two different view models and create different mappings for each one.


回答1:


The Ignore() feature is strictly for members you never map, as these members are also skipped in configuration validation. I checked a couple of options, but it doesn't look like things like a custom value resolver will do the trick.

Use the Condition() feature to map the member when the condition is true:

Mapper.CreateMap<CarViewModel, Car>()
 .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id != 0))



回答2:


I ran into a similar issue, and while this will overwrite the existing value for dest.Code with null, it might be helpful as a starting point:

AutoMapper.Mapper.CreateMap().ForMember(dest => dest.Code,config => config.MapFrom(source => source.Id != 0 ? null : source.Code));




回答3:


Here is the documentation of the conditional mapping: http://docs.automapper.org/en/latest/Conditional-mapping.html

There's also another method called PreCondition very useful on certain scenarios since it runs before the source value is resolved in the mapping process:

Mapper.PreCondition<CarViewModel, Car>()
 .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id == 0))


来源:https://stackoverflow.com/questions/2451189/automapper-ignore-on-condition-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!