How to configure Conditional Mapping in AutoMapper?

后端 未结 4 1400
花落未央
花落未央 2020-12-13 17:48

Suppose I have the following entities (classes)

public class Target
{
    public string Value;
}


public class Source
{
    public string Value1;
    public         


        
相关标签:
4条回答
  • 2020-12-13 18:05

    With the conditional mapping you only can configure when the mapping should executed for the specified destination property.

    So it means you can't define two mappings with different conditions for the same destination property.

    If you have a condition like "if condition is true then use PropertyA else use PropertyB" then you should do it like "Tejal" wrote:

    opt.MapFrom(src => src.Value1.StartsWith("A") ? src.Value1 : src.Value2)
    
    0 讨论(0)
  • 2020-12-13 18:08

    AutoMapper allows you to add conditions to properties that must be met before that property will be mapped.

    I was doing the mapping with some enum conditions, have a look that is little effort for the community from my side.

    }

    .ForMember(dest => dest.CurrentOrientationName, 
                 opts => opts.MapFrom(src => src.IsLandscape? 
                                            PageSetupEditorOrientationViewModel.Orientation.Landscape : 
                                            PageSetupEditorOrientationViewModel.Orientation.Portrait));
    
    0 讨论(0)
  • 2020-12-13 18:15

    AutoMapper allows adding conditions to properties that must be met before that property will be mapped.

    Mapper.CreateMap<Source,Target>()
          .ForMember(t => t.Value, opt => 
                {
                    opt.PreCondition(s => s.Value1.StartsWith("A"));
                    opt.MapFrom(s => s.Value1);
                })
    
    0 讨论(0)
  • 2020-12-13 18:19

    Try this

     Mapper.CreateMap<Source, Target>()
            .ForMember(dest => dest.Value, 
                       opt => opt.MapFrom
                       (src => src.Value1.StartsWith("A") ? src.Value1 : src.Value2));
    

    Condition option is used to add conditions to properties that must be met before that property will be mapped and MapFrom option is used to perform custom source/destination member mappings.

    0 讨论(0)
提交回复
热议问题