c# - AutoMapper - 一对多映射

标签 c# automapper

我在将带有嵌套列表的一个源对象映射到多个目标对象时遇到问题。由于项目限制,我只能修改部分代码。我正在使用 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()
        );
});

关于c# - AutoMapper - 一对多映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804746/

相关文章:

c# - 奇怪的系统.__佳能异常(exception)

c# - 正则表达式围绕大括号拆分

c# - 以编程方式将报告分配给我的 reportViewer

c# - Automapper - 如何从源子对象映射到目标

automapper - Autofac 和 Automapper

c# - 无法将 System.Uri 类型隐式转换为字符串

c# - 在类声明中初始化对象与构造函数的区别

c# - 下拉菜单的自动映射器映射 IEnumerable<SelectListItem>

c# - 如果在 AutoMapper ForMember 中还有

NHibernate、AutoMapper 和 ASP.NET MVC