简体   繁体   English

Automapper 配置文件将具有嵌套列表的对象映射到目标列表

[英]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 .我想映射Source -> List<Destination> ,其中Destination中的项目数等于SourceFooBar的数量,但它们也都有来自SourceIdDescription

.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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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