2016-10-01 132 views
3

我在中遇到了一个问题,即将一个带有嵌套列表的源对象映射到多个目标对象。至于项目限制,我只能调整部分代码。我正在使用AutoMapper 5.1。AutoMapper - 一对多映射

/// no changes possible 
namespace Source 
{ 
    class Person 
    { 
     public string Name { get; set; } 
     public List<Car> Cars { get; set; } 

     public Person() 
     { 
      Cars = new List<Car>(); 
     } 
    } 

    class Car 
    { 
     public string NumberPlate { get; set; } 
    } 
} 

/// no changes possible 
namespace Destination 
{ 
    class PersonCar 
    { 
     public string Name { get; set; } 
     public string NumberPlate { get; set; } 
    } 
} 

/// Demo Consolen Application 
static void Main(string[] args) 
{ 
    #region init data 
    Person person = new Person(); 
    for (int i = 0; i < 10; i++) 
    { 
     person.Cars.Add(new Source.Car() { NumberPlate = "W-100" + i }); 
    } 
    #endregion 

    /// goal is to map from one person object o a list of PersonCars    
    Mapper.Initialize(
     cfg => cfg.CreateMap<Person, List<PersonCar>>() 
      /// this part does not work - and currently I am stuck here 
      .ForMember(p => 
      { 
       List<PersonCar> personCars = new List<PersonCar>(); 

       foreach (Car car in p.Cars) 
       { 
        PersonCar personCar = new PersonCar(); 
        personCar.Name = p.Name; 
        personCar.NumberPlate = car.NumberPlate; 
        personCars.Add(personCar); 
       } 
       return personCars; 
      }) 
    ); 

    // no changes possible 
    List<PersonCar> result = Mapper.Map<Person, List<PersonCar>>(person); 
} 

}

现在,我被困在确定这一问题的适当映射。虽然我在workt做了(丑陋!!)映射(左代码在那里.. facepalm)我确信必须有一个简单的解决方案来解决这个问题。

任何帮助,将不胜感激!

回答

3

您可以使用.ConstructProjectionUsing方法,以提供您想要的实体的投影。

Mapper.Initialize(cfg => { 
    cfg.CreateMap<Person, List<PersonCar>>() 
     .ConstructProjectionUsing(
      p => 
       p.Cars.Select(c => new PersonCar { Name = p.Name, NumberPlate = c.NumberPlate }) 
       .ToList() 
     ); 
}); 
+0

非常感谢! –

+0

这基本上只是做常规的映射。 – Proximo