Flatten and map objects inner collection to another collection

时间:2015-05-04 19:29:05

标签: c# automapper

I have a source enumeration which holds an inner enumeration, 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.

1 个答案:

答案 0 :(得分:1)

My approach would be to keep the enumerable out of the CreateMap definition...keep that type based for a single object.

    Mapper.CreateMap<SourceInnerClass, DestinationClass>();

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