简体   繁体   English

AutoMapper 映射集合到嵌套对象集合

[英]AutoMapper mapping collection to nested objects collection

I am trying to map an object with a collection property to another object with a nested class containing mapped versions of the source collections, but I can't seem to figure out the appropriate mapping required.我正在尝试将 map 和具有集合属性的 object 连接到另一个 object,其嵌套 class 包含源 collections 的映射版本,但我似乎无法弄清楚所需的适当映射。

Below are my class and attempted mappings.下面是我的 class 和尝试映射。

public class TypeA
{
    public int Id;
    public string Description;
}

public class TypeB
{
    public int Id;
    public int Code;
}

public class Source
{
    public ICollection<TypeA> A;
    public ICollection<TypeB> B;
}

public class Destination
{
    public DestinationInner Inner;
}

public class DestinationInner
{
    public ICollection<int> A;
    public ICollection<int> B;
}

I have the following mappings defined, which works fine when the destination collection is at the parent level and not in the DestinationInner class.我定义了以下映射,当目标集合处于父级别而不是 DestinationInner class 时,它工作正常。

Mapper.CreateMap<TypeA, int>()
          .ConvertUsing(a => a.Id);

Mapper.CreateMap<TypeB, int>()
          .ConvertUsing(b => b.Id);

I've tried adding a map such as, but I can't find a way of forcing a mapping here on the collections我试过添加一个 map,例如,但我找不到在 collections 上强制映射的方法

Mapper.CreateMap<Source, Destination>()
          .ForMember(d => d.Inner,
                     opt.MapFrom(s => new DestinationInner()
                                      {
                                          // not sure if I can assign anything here
                                          A = 
                                          B = 
                                      }));

Is MapFrom the appropriate method to use here - or am I approaching this from the wrong direction? MapFrom 是适合在这里使用的方法吗 - 或者我是从错误的方向接近这个?

The alternative is to not use AutoMapper for the collections and just use Linq, but I'm thinking there has to be a way to fully use AutoMapper:另一种方法是不对 collections 使用 AutoMapper,而只使用 Linq,但我认为必须有一种方法可以充分使用 AutoMapper:

Mapper.CreateMap<Source, Destination>()
          .ForMember(d => d.Inner,
                     opt.MapFrom(s => new DestinationInner()
                                      {
                                          A = s.A.Select(a => a.Id).ToList(),
                                          B = s.B.Select(b => b.Id).ToList(),
                                      }));

Lucian provided the answer in the comments:卢锡安在评论中给出了答案:

ForPath(d => d.Inner.A, o => o.MapFrom(s => s.A))

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

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