How to use automapper to map parent child relation ship between model and viewmodel

asp.net-mvc asp.net-mvc-5 automapper entity-framework entity-framework-6

Question

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;}

}

I want to map my fooViewModel which have child objects to Boo Model using automapper and vice versa from Boo model to FooViewModel. Kindly help me how I can achieve this scenario. If there is any other easy way to map Viewmodel to Domain Model and Domain Model to ViewModel kindly explain it.

1
2
11/18/2016 3:12:41 PM

Accepted Answer

I'll presume you already know how to wire up AutoMapper. Then the configuration could look like this:

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>();

and then simply

var boo = Mapper.Map<Boo>(fooViewModelObject);
1
11/20/2016 8:42:48 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow