Using SqlQuery to get IQueryable

2019-02-16 07:59发布

问题:

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")

Problem is that SqlQuery returns DbRawSqlQuery which is IEnumerable.

dbo.SomeDynamicView is a database view created at runtime.

回答1:

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.