Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper unable to project one enum type to another

I'm leveraging the Project functionality in Automapper and Entity Framework, but I'm running into an issue where Automapper doesn't seem to want to project one enum type to another.

I have the following entities:

public class UserProfile
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    private HashSet<UserProfilePhone> m_Phones;
    public virtual HashSet<UserProfilePhone> Phones
    {
        get { return m_Phones ?? (m_Phones = new HashSet<UserProfilePhone>()); }
        set { this.m_Phones = value; }
    }
}

public class UserProfilePhone
{
    public PhoneType Type { get; set; }
    public virtual string Number { get; set; }
}

public enum PhoneType
{
    Home = 1,
    Work = 2,
    Mobile = 3,
    Other = 4
}

I then am projecting these types to the following models:

public class UserProfileModel
{
    public Guid Id { get; set; }
    public virtual string Name { get; set; }
    public IEnumerable<UserProfilePhoneModel> Phones { get; set; }
}

public class UserProfilePhoneModel
{
    public UserProfilePhoneTypeModel Type { get; set; }
    public string Number { get; set; }        
}

public enum UserProfilePhoneTypeModel
{
    Home = 1,
    Work = 2,
    Mobile = 3,
    Other = 4
}

I then setup my mappings like so:

Mapper.CreateMap<PhoneType, UserProfilePhoneTypeModel>();
Mapper.CreateMap<UserProfilePhone, UserProfilePhoneModel>();
Mapper.CreateMap<UserProfile, UserProfileModel>();

And finally I'm executing my projection:

var result = dbContext.UserProfiles.Project().To<UserProfileModel>();

When I do this, I get the following exception:

AutoMapper.AutoMapperMappingException: Unable to create a map expression from MyNamespace.PhoneType to MyNamespace.Models.UserProfilePhoneTypeModel Unable to create a map expression from MyNamespace.PhoneType to MyNamespace.Models.UserProfilePhoneTypeModel Result StackTrace:
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) ...

I've tried creating explicit mappings, but they appear to be ignored. What am I doing wrong here?

like image 420
RMD Avatar asked Sep 17 '14 17:09

RMD


1 Answers

As usual, I figured out the answer almost as soon as I posted the question.

Modifying the create map line to provide an explicit cast did the trick:

Mapper.CreateMap<UserProfilePhone, UserProfilePhoneModel>()
    .ForMember(m => m.Type, opt => opt.MapFrom(t => (UserProfilePhoneTypeModel)t.Type));
like image 102
RMD Avatar answered Oct 13 '22 04:10

RMD