Automapper, MapFrom and EF dynamic proxies

2019-02-19 19:35发布

问题:

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.

回答1:

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.



回答2:

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