Search code examples
c#asp.netautomapperkenticokentico-kontent

Prevent Automapper converting IEnumerable Property to List


I'm trying to map a Model to a ViewModel that has properties of types that inherit from IEnumerable. The properties are of the same type and name, but Automapper is converting the source to a Generic List and then failing to map to the destination.

These are the classes I'm trying to map:

BasicOverview
{
   public IRichTextContent Intro { get; set; }
   ...
}

BlogOverviewViewModel
{
   public IRichTextContent Intro { get; set; }
   ...
}

The following is third party code where the IRichTextContent type is defined:

//     Represents rich text content in a form of structured data
public interface IRichTextContent : IEnumerable<IRichTextBlock>, IEnumerable
{
    //
    // Summary:
    //     List of rich text content blocks
    IEnumerable<IRichTextBlock> Blocks { get; set; }
}

My Automapper Profile:

public AutomapperProfile()
    {
        CreateMap<BasicOverview, BlogListViewModel>();
        CreateMap<BasicOverview, ReviewListViewModel>();
        CreateMap<BasicOverview, BlogOverviewViewModel>();
    }

And this is the error I get:

An unhandled exception occurred while processing the request. InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[KenticoCloud.Delivery.IRichTextBlock]' to type 'KenticoCloud.Delivery.IRichTextContent'. lambda_method(Closure , BasicOverview , BlogOverviewViewModel , ResolutionContext )

AutoMapperMappingException: Error mapping types.

Mapping types: BasicOverview -> BlogOverviewViewModel

Type Map configuration: BasicOverview -> BlogOverviewViewModel

Destination Member: Intro lambda_method(Closure , BasicOverview , BlogOverviewViewModel , ResolutionContext )

I tried adding the following to my Automapper Profile:

CreateMap<IEnumerable<IRichTextBlock>, IRichTextContent>()
            .ForMember(dest => dest.Blocks, m => m.MapFrom(src => src));

Which produced the following error:

TypeLoadException: Method 'GetEnumerator' in type 'Proxy_KenticoCloud.Delivery.IRichTextContent_12345678_' from assembly 'AutoMapper.Proxies, Version=0.0.0.0, Culture=neutral, PublicKeyToken=abc123ef45' does not have an implementation.


Solution

  • Just to make the answer from Lucian Bargaoanu's comment more visible.

    One of the solutions is to add following mapping to the Automapper profile:

    CreateMap<IRichTextContent, IRichTextContent>().ConvertUsing(s=>s);