使用SqlQuery获取IQueryable [英] Using SqlQuery to get IQueryable
问题描述
这是一个可以返回实体框架6中的动态SQL查询的 IQueryable
我现在正在使用,但它正在拉出所有的记录(如预期)。
DbContext.Database.SqlQuery< T>(SELECT * FROM dbo.SomeDynamicView)
问题是 SqlQuery
返回 DbRawSqlQuery
这是 IEnumerable
。
dbo.SomeDynamicView
是一个数据库视图
不,你不能得到一个 IQueryable
从 SqlQuery
* ,这是因为 IQueryable
正在做的是构建SQL字符串动态地基于什么选择和您放置的过滤器。因为在 SqlQuery
中,您提供的字符串Entity Framework无法生成该动态字符串。
您的选项是动态构建您的自我传递给 SqlQuery
的字符串,并将其用作 IEnumerable
而不是 IQueryable
或在您的 DbContext 中使用
DbSet
code>并且做更多的正常的方式让实体框架为您构建查询。
< sup> *您技术上可以通过致电 AsQueryable( )的结果,但这只是一个IEnumerable假装是一个IQueryable,它不给你任何使用真正的IQueryable的好处,只需从服务器检索所需的行。
Is there something that can return IQueryable
for 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")
Problem is that SqlQuery
returns DbRawSqlQuery
which is IEnumerable
.
dbo.SomeDynamicView
is a database view created at runtime.
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.
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.
* 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屋!