Mapping items from one class to another if Items are equivalent

前端 未结 4 1353
鱼传尺愫
鱼传尺愫 2021-01-16 02:53

Say I have one class that looks like this:

public class Person
{
     public string Name {get; set;}
     public int Number {get; set;}
}
         


        
4条回答
  •  [愿得一人]
    2021-01-16 03:08

    Install AutoMapper package in your project.

    As a best practice (for web applications) you can create new class (should derives from Profile) in your App_Start folder, that will contain all your mappings for your project.

    namespace MyApp.App_Start
    {
        public class MyAppMapping : Profile
        {
            public MyAppMapping()
            {
    
                CreateMap();
    
                //You can also create a reverse mapping
                CreateMap();
    
                /*You can also map claculated value for your destination. 
                Example: you want to append "d-" before the value that will be
                mapped to Name property of the dog*/
    
                CreateMap()
                .ForMember(d => d.Days, 
                 conf => conf.ResolveUsing(AppendDogName)); 
            }
    
            private static object AppendDogName(Person person)
            {
                return "d-" + person.Name;
            }
        }
    }
    

    Then Initialize your mapping inside the Application_Start method in Global.asax

    protected void Application_Start()
    {
        Mapper.Initialize(m => m.AddProfile());
    }
    

    You can now use the mappings that you have created

    var dog = AutoMapper.Mapper.Map(person);
    

提交回复
热议问题