2011-02-01 51 views
1

我有一个类似的嵌套的视图模型:Automapper如何从嵌套模型工作到平面模型?

public class EmployeeViewModel 
{  
    //... 

    public string EmployeeFirstName { get; set; } 

    public string EmployeeLastName { get; set; } 

    public AddressViewModel{ get; set; } 
} 

的AddressViewModel看起来是这样的:

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

然后,有一个员工的域对象,像这样:

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

我试图将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 2014-10-10 15:04:28