Question

I am trying to use AutoMapper to map a very simple Enum.

The reason this mapping exists is PriorityType is in my dotnet 4.0 domain model assembly that runs on the server, but I need the Dto in dotnet 3.5 in my DataContract assembly.

public enum PriorityType// : byte
{
    Low = 0,
    Medium,
    High,
    Urgent
}

[Serializable]
public enum PriorityTypeDto// : byte
{
    Low = 0,
    Medium,
    High,
    Urgent
}

Mapper.CreateMap<PriorityType, PriorityTypeDto>();

If I uncomment out the byte parent type (I really don't need more than 255 possible entries!), I get a TypeInitializationException. Haven't been able to work around it using ConvertUsing either.

Why the hiccup around byte?

Edit 1

Debugging AutoMapper further, it essentially retrieves all the writable properties in the destination and checks for a corresponding property with the same name.

In the case of Enums there is a field named value__ that is visible with reflection that AutoMapper attempts to map.

The error is different with v2.2 (was on 2.1) but still it throws an exception when mapping enums of bytes but does just fine when mapping enums of int32.

The error occurs here,

public delegate object LateBoundFieldGet(object target);

Expression<LateBoundFieldGet> lambda =
    Expression.Lambda<LateBoundFieldGet>(
        Expression.Convert(member, typeof(object)),
        instanceParameter);

return lambda.Compile();

The lambda.Compile() throws an InvalidProgramException.

Still trying to understand why.

Edit 2

Issue reported on AutoMapper GitHub as well.

Was it helpful?

Solution

You don't need the CreateMap call - AutoMapper automatically handles enum types without any configuration. Just remove CreateMap and you're set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top