Strange Automapper definition when mapping IDictionary to IDictionary

Viewed 78

guys.

I have a strange definition of Automapper when I try to map one IDictionary<int, int> to IDictionary<int, int> or IDictionary<int, int> to IDictionary<string, int>.

So, let's have 2 classes:

public class OrderProfile 
{
    public IDictionary<int, int> CountableAuxElements { get; set; } 
}

public class OrderProfileResponse 
{
    public IDictionary<int, int> CountableAuxElements { get; set; }
    public IDictionary<string, int> CountableAuxElementsString { get; set; } 
}

So, when I create a new map through

CreateMap<OrderProfile, OrderProfileResponse>().ForMember(e => e.CountableAuxElementsString, f => f.Ignore()), 

I get an error like this:

Unable to cast object of type 'System.Collections.Generic.List'1[System.Collections.Generic.KeyValuePair'2[System.Int32,System.Int32]]' to type 'System.Collections.Generic.IDictionary`2[System.Int32,System.Int32]'.

I tried to write code like this:

CreateMap<OrderProfile, OrderProfileResponse>().ForMember(e => e.CountableAuxElements, f => f.MapFrom(s => s.CountableAuxElements.ToDictionary(f => f.Key, f => f.Value)))

or this:

CreateMap<OrderProfile, OrderProfileResponse>().ForMember(e => e.CountableAuxElements, opt => opt.ConvertUsing(new DictionaryConversation<int, int, int, int>((p, context) => p, (p, context) => p), src => src.CountableAuxElements))

where:

internal class DictionaryConversation<TOldKey, TOldValue, TNewKey, TNewValue> : IValueConverter<IDictionary<TOldKey, TOldValue>, IDictionary<TNewKey, TNewValue>>
{
    private readonly Func<TOldKey, ResolutionContext, TNewKey> keyModifier;
    private readonly Func<TOldValue, ResolutionContext, TNewValue> valueModifier;

    public DictionaryConversation(Func<TOldKey, ResolutionContext, TNewKey> keyModifier, Func<TOldValue, ResolutionContext, TNewValue> valueModifier)
    {
        this.keyModifier = keyModifier;
        this.valueModifier = valueModifier;
    }

    public virtual IDictionary<TNewKey, TNewValue> Convert(IDictionary<TOldKey, TOldValue> sourceMember, ResolutionContext context) =>
               sourceMember.ToDictionary(e => keyModifier(e.Key, context), e => valueModifier(e.Value, context));
}

but with the same error. The same error I have for CountableAuxElementsString when mapping it through the ToDictionary or DictionaryConversation.

What's the reason for this error? I've really had my head broken...

Thank you.

0 Answers
Related