如何使用automapper在model和viewmodel之间映射父子关系

时间:2016-11-17 19:35:20

标签: asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6 automapper

public class fooViewModel{
public int id {get; set;}
public string companyname {get; set;}
public string companyaddress {get; set;}

public EmployeeViewModel CotactPerson  {get; set;} 
public EmployeeViewModel Manager {get; set;} 

}

public class EmployeeViewModel {
public int id {get; set;}
public string employeename {get; set;}
public string mobile {get; set;}
}


public class Boo {

public int id {get; set;}
public string name{get; set;}
public string address {get; set;}

public Icollection<Employee> Employee {get; set;}

}


public class Employee
{

public int id {get; set;}
public int fooid {get; set;}
public foo foo {get; set;}
public int Booid {get; set;}
public string employeename {get; set;}
public string mobile {get; set;}
public datetime DateOfBirth {get; set;}
public string PlaceOfBirth{get; set;}
}


public class foo {

public int id {get; set;}
public string companyname {get; set;}
public string companyaddress {get; set;}
public string Email{get; set;}
public DateTime EstablismentDate{get; set;}

}

我想使用automapper将具有子对象的fooViewModel映射到Boo Model,反之亦然,从Boo模型映射到FooViewModel。请帮助我如何实现这种情况。如果有任何其他简单的方法将Viewmodel映射到域模型,将域模型映射到ViewModel,请解释它。

1 个答案:

答案 0 :(得分:0)

我假设您已经知道如何连接AutoMapper。然后配置可能如下所示:

Mapper.CreateMap<fooViewModel, Boo>()
    .ForMember(d => d.name, o => o.MapFrom(s => s.companyname))
    .ForMember(d => d.address, o => o.MapFrom(s => s.companyaddress))
    .ForMember(d => d.Employee, o => o.MapFrom(s => new Collection<EmployeeViewModel> { s.CotactPerson, s.Manager }));

Mapper.CreateMap<EmployeeViewModel, Employee>();

然后简单地

var boo = Mapper.Map<Boo>(fooViewModelObject);