使用 SqlQuery 获取 IQueryable [英] Using SqlQuery to get IQueryable

查看:9
本文介绍了使用 SqlQuery 获取 IQueryable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体框架 6 中的动态 sql 查询是否可以返回 IQueryable?

Is there something that can return IQueryablefor a dynamic sql query in Entity Framework 6?

这是我现在使用的,但它正在提取所有记录(如预期的那样).

This is what I am using now but it is pulling all the records (as expected).

DbContext.Database.SqlQuery<T>("SELECT * FROM dbo.SomeDynamicView")

问题是 SqlQuery 返回 DbRawSqlQueryIEnumerable.

dbo.SomeDynamicView 是在运行时创建的数据库视图.

dbo.SomeDynamicView is a database view created at runtime.

推荐答案

不,你不能从 SqlQuery* 获取 IQueryable,这是因为 IQueryable 正在做的是根据您输入的选择和位置过滤器动态构建 SQL 字符串.因为在 SqlQuery 您提供的字符串 Entity Framework 可以不生成该动态字符串.

No, you can't get a IQueryable from SqlQuery*, this is because what IQueryable is doing is building a SQL string dynamically based on what select and where filters you put in. Because in SqlQuery you are providing the string Entity Framework can not generate that dynamic string.

您的选择是动态构建您自己的字符串以传递给 SqlQuery 并将其用作 IEnumerable 而不是 IQueryable 或在您的 DbContext 中使用 DbSet 并以更正常"的方式让实体框架为您构建查询.

Your options are either dynamically build the string your self to pass in to SqlQuery and use it as a IEnumerable instead of a IQueryable or use a DbSet in your DbContext and do the more "normal" way of letting entity framework build the query for you.

* 从技术上讲,您可以通过调用 AsQueryable() 结果,但这只是一个伪装成 IQueryable 的 IEnumerable,它不会为您提供使用真实"IQueryable 的任何好处,例如仅从服务器检索所需的行.

* You technically can by calling AsQueryable() on the result, but that is just a IEnumerable pretending to be a IQueryable, it does not give you any of the benefits of using a "Real" IQueryable like only retrieving the needed rows from the server.

这篇关于使用 SqlQuery 获取 IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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