Automapper,MapFrom和EF动态代理

编程入门 行业动态 更新时间:2024-10-27 07:15:30
本文介绍了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动态代理

本文发布于:2023-11-14 10:39:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586993.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   Automapper   MapFrom   EF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!