简体   繁体   English

展平并将对象内部集合映射到另一个集合

[英]Flatten and map objects inner collection to another collection

I have a source enumeration which holds an inner enumeration, IEnumerable<>. 我有一个包含内部枚举IEnumerable <>枚举 I want to be able to take my sources inner enumeration and flatten it out into my destination enumeration. 我希望能够将源内部的枚举取整并整理到目标枚举中。 However, when I attempt the following code below, I am prompted with an exception stating that this is an invalid mapping. 但是,当我尝试以下代码时,系统会提示我异常,指出这是无效的映射。

public class DestinationClass 
{
   string Name {get; set;}
}

public class SourceClass
{
   IEnumerable<SourceInnerClass> InnerCollection {get; set;}
}

public class SourceInnerClass
{
   string Name {get; set;}
}

// Mapping Configuration

Mapper.CreateMap<SourceInnerClass, DestinationClass>();

Mapper.CreateMap<SourceClass, IEnumerable<DestinationClass>>()
                .ForMember(dest => dest,
                opts => opts.MapFrom(source => source.InnerCollection));

// Implementation

IEnumeration<SourceClass> sourceCollection = GetSourceDataEnumeration();

var results = Mapper.Map<IEnumeration<DestinationClass>>(sourceCollection);

I've tried many different variations of the code above, and I can't seem to figure out where I am going wrong. 我已经尝试了上面代码的许多不同变体,但似乎无法弄清楚哪里出了问题。 I'm either prompted that I cannot map at a "parent level" or that the mapping does not exist. 提示我不能在“父级”映射,或者该映射不存在。

If I were manually mapping, I would essentially want to do the following, however, auto mapper complains this construction is invalid: 如果我是手动映射,则本质上我想执行以下操作,但是,自动映射器会抱怨这种构造无效:

var destination = source.InnerCollection.Select(s => new DestinationClass { Name = s.Name }

The exact error I get is, 我得到的确切错误是

Additional information: Custom configuration for members is only supported for top-level individual members on a type. 附加信息:类型的顶级单个成员仅支持成员的自定义配置。

My approach would be to keep the enumerable out of the CreateMap definition...keep that type based for a single object. 我的方法是将可枚举数保留在CreateMap定义之外...让该类型基于单个对象。

    Mapper.CreateMap<SourceInnerClass, DestinationClass>();

    var results = sourceCollection.SelectMany(sm=>sm.InnerCollection).Select(s=>Mapper.Map<DestinationClass>(s));

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

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