![](/img/trans.png)
[英]How to map a somewhat complex architecture with automapper and constructUsing
[英]How to map complex class with automapper
我必须为VM和GM命名空间。 两者都有Employee类。 员工包含部门。 我想将VM.Employee映射到GM.Employee。 映射器不允许我映射部门。
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;}
}
实际上,这并不困难。 您可以按字段手动映射字段,如下所示:
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可能无法知道您要映射到哪些字段,因此必须明确地告诉它。
您当然应该阅读AutoMapper文档以获取更多信息: Automapper文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.