How to specify mapping rule when names of properties differ

后端 未结 4 1724
孤独总比滥情好
孤独总比滥情好 2020-11-29 19:53

I am a newbie to the Automapper framework. I have a domain class and a DTO class as follows:

public class Employee
{
   public long Id {get;set;}
   public s         


        
相关标签:
4条回答
  • 2020-11-29 19:56

    We can also specify on Class attributes for mapping

    From https://docs.automapper.org/en/stable/Conventions.html#attribute-support

    Attribute Support

    AddMemberConfiguration().AddName<SourceToDestinationNameMapperAttributesMember>(); * Currently is always on

    Looks for instances of SourceToDestinationMapperAttribute for Properties/Fields and calls user defined isMatch function to find member matches.

    MapToAttribute is one of them which will match the property based on name provided.

    public class Foo
    {
        [MapTo("SourceOfBar")]
        public int Bar { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-29 20:08

    Just to roll the comments above into an updated approach using Automapper 8.1+...

    var mapConfig = new MapperConfiguration(
       cfg => cfg.CreateMap<Employee, EmployeeDto>()
          .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
    );
    

    Then you would build the mapper using the mapConfig:

    var mapper = mapConfig.CreateMapper();
    
    0 讨论(0)
  • 2020-11-29 20:15

    Considering that we have two classes

    public class LookupDetailsBO
        {
            public int ID { get; set; }
    
            public string Description { get; set; }
    
        }
    

    and the other class is

    public class MaterialBO
        {
            [MapTo(nameof(LookupDetailsBO.ID))]
            public int MaterialId { get; set; }
    
            [MapTo(nameof(LookupDetailsBO.Description))]
            public string MaterialName { get; set; }
    
            public int LanguageId { get; set; }
        }
    

    In this way you know typically to which property you follow . and you make sure of the naming convention , so if you have changed the propery name in the source . The MapTo() will prompt an error

    0 讨论(0)
  • 2020-11-29 20:23

    Never mind, I myself found a solution:

    Mapper.CreateMap<Employee, EmployeeDto>()
        .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));
    
    0 讨论(0)
提交回复
热议问题