获取实体框架原始查询以尊重属性 [英] getting Entity Framework raw query to respect attributes

查看:38
本文介绍了获取实体框架原始查询以尊重属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF4,请先编写代码。这样,我的模型类混合了一些公共属性,一些虚拟属性(用于从其他表中延迟加载的数据)和一些附加了 [NotMapped] 属性的属性,因此被EF跳过。

I'm using EF4, code first. As such, my model classes have a mix of public properties, some virtual properties (for lazy loaded data from other tables) and some properties that are affixed with [NotMapped] attributes so that they are skipped by EF.

有时候我喜欢使用原始查询: c.Database.SqlQuery&T;>( select ...)以将EF用作行映射器。

Sometimes I like to make use of the raw query : c.Database.SqlQuery<T>("select ...") to use EF as a row mapper.

我在Intellitrace中注意到,这些查询为 IndexOutOfRange生成了大量引发和捕获的异常。经过一番观察,所有异常都属于模型对象的virtual和[NotMapped]属性。我不想只使用表属性来构造一个新的数据模型类或父类;我是否缺少一些配置步骤来告诉原始查询运行器中的行映射器注意其余EF使用的相同注释?也许他们在EF5中解决了这个问题?

I noticed in Intellitrace that these queries were generating a lot of thrown and caught exceptions for "IndexOutOfRange". After some looking, the exceptions are all for the virtual and [NotMapped] properties on the model object. I don't want to have to construct a new data model class or parent class with just the table properties in it; is there some configuration step I've missed to tell the row mapper in the raw query runner to pay attention to the same annotations that the rest of EF uses? Maybe they fixed this in EF5?

推荐答案

如果执行 dbContext.Database.SqlQuery EF将永远不会使用映射。它将只使用属性名称和结果集中的列的简单匹配。尝试改用 dbSet.SqlQuery 。它应该反映映射,因为它可以将数据作为附加实体加载。

If you execute dbContext.Database.SqlQuery EF will never use mapping. It will use just simple match of property names and columns in result set. Try to use dbSet.SqlQuery instead. It should reflect mapping because it can load data as attached entities.

这篇关于获取实体框架原始查询以尊重属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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