Automapper, MapFrom and EF dynamic proxies

automapper c# entity-framework


I have been trying to map my domain objects to a report view model. Things all worked well in testing where I faked the entity framework code out and used a builder to return a fully populated pocco object. Now that I am actually hitting the database and returning data I am seeing some wierd dynamic proxy type errors.

Here is a sample of my code:

public class ContactMapping  : Profile
    protected override void Configure()
        Mapper.CreateMap<Contact, ReportRowModel>()
             .ForMember(dest => dest.Gender, opt => opt.MapFrom(src => src.Gender.Name));



And the mapping code is like this:

var contact = GetContactFor(clientPolicy);
Mapper.DynamicMap(contact, rowModel);
return rowModel;

The contact fields all populate correctly except for the rowModel.Gender field which is returning System.Data.Entity.DynamicProxies.Gender_3419AAE86B58120AA2983DA212CFFEC4E42296DA14DE0836B3E25D7C6252EF18

I have seen solutions where people have had problems using Map instead of DynamicMap, but I haven't found anything where a .ForMember mapping is failing like this.

Any suggestions.

8/26/2014 1:45:35 PM

Accepted Answer

Your EF query is not returning the Gender, it is returning a Proxy that can get Gender for you when evaluated, which is not of the type that AutoMapper built a mapping to handle.

You either need to eagerly fetch Gender in your query, or use AutoMapper's IQueryable Extention's Project method to have AutoMapper emit an anonymous projection (again, in your query), rather than try to apply the AutoMapping after the result has been returned from your EF context.

This is good practice in general to avoid Select N+1 issues.

8/26/2014 2:05:17 PM

Popular Answer

I've got the same issue right now with version 4.x, reverting to 3.3.1 fixed the issue.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow