2011-02-01 7 views
1

나는이 비슷한 중첩 된 뷰 모델을 가지고 :Automapper는 중첩 모델에서 평면 모델로 어떻게 작동합니까?

public class EmployeeViewModel 
{  
    //... 

    public string EmployeeFirstName { get; set; } 

    public string EmployeeLastName { get; set; } 

    public AddressViewModel{ get; set; } 
} 

AddressViewModel은 다음과 같습니다

public class Employee 
{ 
    public string EmployeeFirstName { get; set; } 

    public string EmployeeLastName { get; set; } 

    public string Street { get; set; } 

    public string City { get; set; } 

    public string State { get; set; } 

    public string Zip { get; set; } 
} 

I :

public class AddressViewModel 
{ 
    public string Street {get; set;} 
    public string City {get; set;} 
    public string State {get; set;} 
    public string Zip {get; set;} 
} 

그런 다음, 그래서 같은 직원 도메인 개체있다 EmployeeViewModel을 Employee 도메인 객체에 매핑하려고합니다. 이것은 내가 무엇을 최대 온이며 작동하지만이 할 수있는 쉬운 방법이 있는지 궁금 해서요 : 당신이 볼 수 있듯이

Mapper.CreateMap<EmployeeViewModel, Employee>().ForMember(destination => destination.Street, opt => opt.MapFrom(src => src.AddressViewModel.Street)) 
      .ForMember(destination => destination.City, opt => opt.MapFrom(src => src.AddressViewModel.City)) 
      .ForMember(destination => destination.State, opt => opt.MapFrom(src => src.AddressViewModel.State)) 
      .ForMember(destination => destination.Zip, opt => opt.MapFrom(src => src.AddressViewModel.Zip)); 

, 직원 도메인 개체의 속성 이름과 AddressViewModel이됩니다 같은. 그래서, 이것을하기위한 더 쉬운 방법이있는 것처럼 보입니다.

감사

답변

2

당신은 문서의 flattening sample을 체크 아웃 할 수 있습니다. 그리고 여기에 예는 다음과 같습니다

public class AddressViewModel 
{ 
    public string Street { get; set; } 
} 

public class EmployeeViewModel 
{  
    public string EmployeeFirstName { get; set; } 
    public AddressViewModel Address { get; set; } 
} 

public class Employee 
{ 
    public string EmployeeFirstName { get; set; } 
    public string AddressStreet { get; set; } 
} 


class Program 
{ 
    static void Main() 
    { 
     Mapper.CreateMap<EmployeeViewModel, Employee>(); 
     var result = Mapper.Map<EmployeeViewModel, Employee>(new EmployeeViewModel 
     { 
      EmployeeFirstName = "first name", 
      Address = new AddressViewModel 
      { 
       Street = "some street" 
      } 
     }); 
     Console.WriteLine(result.EmployeeFirstName); 
     Console.WriteLine(result.AddressStreet); 
    } 
} 

통지 방법에 대한 대상 속성이 AddressStreet라고 상자 밖으로 작업을 병합.

+0

답변으로 표시해야합니다. 완벽한 착용감. 나는 그것이 어떻게 작동했는지 모르고, 비슷한 문제를 해결했다. – julealgon

관련 문제