Automapper,MapFrom和EF动态代理 [英] Automapper, MapFrom and EF dynamic proxies

查看:305
本文介绍了Automapper,MapFrom和EF动态代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图将域对象映射到报表视图模型.在我伪造实体框架代码并使用生成器返回完全填充的pocco对象的测试中,一切工作都很好.现在,我实际上正在访问数据库并返回数据,我看到了一些奇怪的动态代理类型错误.

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.

以下是我的代码示例:

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

    }

}

映射代码如下:

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

除了返回返回System.Data.Entity.DynamicProxies.Gender_3419AAE86B58120AA2983DA212CFFEC4E42296DA14DE0836B3E25D7C6252EF18

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

我看到了人们使用Map而不是DynamicMap时遇到问题的解决方案,但是我没有发现任何这样的.ForMember映射失败的情况.

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.

任何建议.

推荐答案

您的EF查询未返回Gender,而是返回了一个在评估后可以为您获取Gender的代理,这不是AutoMapper构建的代理类型.映射到句柄.

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.

您要么需要在查询中热切获取Gender,要么使用 AutoMapper的IQueryable扩展的项目使AutoMapper发出匿名投影(再次在您的查询中)的方法,而不是在从EF上下文返回结果之后尝试应用AutoMapping.

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.

通常,这是避免选择N + 1问题的好习惯.

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

这篇关于Automapper,MapFrom和EF动态代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆