简体   繁体   中英

Automapper profile to map object with nested list to destination list

Hard to convey the question in the title. Trying to determine the best way to write an automapper profile to map between two objects into lists but the number of items in the destination list will be equal to the number of items in an internal list on the source object. Please find an example of what I'm after:

public class Destination
{
    public int Id { get; set; }
    public string Description { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
}

public class Source
{
   public int Id { get; set; }
   public string Description { get; set; }
   public List<FooBar> FooBar { get; set; }
}

public class FooBar
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

I would like to map Source -> List<Destination> where the number of items in Destination equals the number of FooBar in Source but they also each have an Id and Description from the Source .

.CreateMap<Source, List<Destination>>()
                    .ConvertUsing(source => source.FooBar.Select(fb => new Destination
                    {
                        Foo = fb.Foo,
                        Bar = fb.Bar,
                        Description = source.Description,
                        Id = source.Id
                    }).ToList()
                )

Obviously, use it like this

var destination = mapper.Map<List<Destination>>(Source);

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