[英]AutoMapper - one to many mapping
將一個帶有嵌套列表的源對象映射到多個目標對象時遇到問題。 由於項目限制,我只能改編部分代碼。 我正在使用AutoMapper 5.1。
/// 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 ),但我確信必須有一個簡單的解決方案來解決這個問題。
任何幫助,將不勝感激!
您可以使用.ConstructProjectionUsing
方法,以提供所需實體的投影。
Mapper.Initialize(cfg => {
cfg.CreateMap<Person, List<PersonCar>>()
.ConstructProjectionUsing(
p =>
p.Cars.Select(c => new PersonCar { Name = p.Name, NumberPlate = c.NumberPlate })
.ToList()
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.