简体   繁体   中英

How to map complex class with automapper

I have to namespaces VM and GM. Both having classes Employee. Employee contain Department. I want to map VM.Employee to GM.Employee. Mapper is not allowing me to map Department.

class VM.Employee 
{
    int Id {get;set;}   
    int Name {get;set;}   
    VM.Department dept{get;set;}
}

class VM.Department 
{
    int Id {get;set;}   
    int Name {get;set;}  
}

class GM.Employee 
{
    int Id {get;set;}
    int Name {get;set;}
    GM.Department dept{get;set;}
}

class GM.Department 
{
    int Id {get;set;}
    int Name {get;set;}
}

Actually, it's not that difficult. You can manually map field by field, something along the lines of this:

       Mapper.CreateMap<VM.Employee, GM.Employee>()
              .ForMember(vm => vm.Department,
                         mapping => mapping.MapFrom(gm => gm.Department))

       Mapper.CreateMap<VM.Department, GM.Department>()
              .ForMember(vm => vm.SomeFieldOfVmDepartment,
                         mapping => mapping.MapFrom(gm => gm.SomeFieldOfGmDepartment))
              .ForMember(vm => vm.AnotherField,
                         mapping => mapping.MapFrom(gm => gm.AnotherField))

Automapper is convention based and will automatically match fields that are named identically, when you map two classes. However, when the classes that you want to map have different fields (names or number of fields differ), Automapper cannot possibly know which of the fields you want to map to, so you have to explicitly tell it so.

You should of course, read AutoMapper docs for more info: Automapper Documentation

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