Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动映射将父子关系转换为具有父子属性的对象_C#_.net Core_Automapper - Fatal编程技术网

C# 自动映射将父子关系转换为具有父子属性的对象

C# 自动映射将父子关系转换为具有父子属性的对象,c#,.net-core,automapper,C#,.net Core,Automapper,我试图让Automapper将父子关系转换为一个包含父子属性的列表 我的结构是这样的 public class ItemEntity { public int Id {get;set;} public string key {get;set;} public IEnumerable<ItemVersionEntity> Versions {get; set;} } public class ItemVersionEntity { public string Nam

我试图让Automapper将父子关系转换为一个包含父子属性的列表

我的结构是这样的

public class ItemEntity {
  public int Id {get;set;}
  public string key {get;set;}
  public IEnumerable<ItemVersionEntity> Versions {get; set;} 
}

public class ItemVersionEntity {
  public string Name {get;set;}
  public DateTime Date {get;set;}
}
因此,如果一个ItemEntity包含一个包含四个ItemVersionEntity的列表,我将得到一个包含四个条目的ItemDto列表

我可以轻松地将ItemEntity映射到ItemDto,也可以轻松地将ItemVersionEntity映射到ItemDto,但是如何“组合”它以返回单个列表呢

public class RepositoryMappingProfile : Profile
{
    public RepositoryMappingProfile()
    {
       CreateMap<ItemEntity , ItemDto>();
       CreateMap<ItemVersionEntity , ItemDto>();

       // what to write here to map to a List<ItemDto> ? 
    }
}

这有什么帮助?我在那里找不到解决我问题的办法,我是不是遗漏了什么?如果没有我,你怎么用手去做?向我们展示代码。我已经更新了问题,并解释了如何在没有自动映射的情况下实现这一点。正如文档所解释的,AM只是一对一的映射,因此解决不匹配的代码,您必须自己编写。但你必须决定我在这一点上有多大帮助。对于仅有的一些属性,也许只需手写即可。
public class RepositoryMappingProfile : Profile
{
    public RepositoryMappingProfile()
    {
       CreateMap<ItemEntity , ItemDto>();
       CreateMap<ItemVersionEntity , ItemDto>();

       // what to write here to map to a List<ItemDto> ? 
    }
}
 List<ItemEntity> all = new List<ItemEntity>() {
        new ItemEntity() {
            Id=1,
            key="a",
            Versions = new List<ItemVersionEntity>() {
                new ItemVersionEntity() { Name="name1", Date=DateTime.Now },
                new ItemVersionEntity() { Name="name2", Date=DateTime.Now },
            }
        }
    };
        
    List<ItemDto> mappedDto = new List<ItemDto>();
    foreach(var ie in all) {
        mappedDto.AddRange(ie.Versions.Select(v => new ItemDto() { Id=ie.Id, key = ie.key,  Name=v.Name, Date = v.Date }));
    }
Id | key | Name  | Date
1  | a   | name1 | 10/09/2020 09:37:14 
1  | a   | name2 | 10/09/2020 09:37:14