简体   繁体   中英

AutoMapper - one to many mapping

I am having problems in mapping one source object with a nested list to multiple destination objects . As of project restrictions I can only adapt parts of the code. I am using 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);
}

}

Right now I am stuck on defining a proper mapping for this problem. Although I did a (ugly!!) mapping at workt (left code there .. facepalm ) I am sure there must be a simple solution for this problem.

Any help would be appreciated!

You can use the .ConstructProjectionUsing method, in order to supply a projection of the entity you desire.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM