问题描述
我有奇怪的错误,当我试图查看SqlQuery类的结果:
VAR SQL =SELECT @someParam
变种someParamSqlParameter =新的SqlParameter(someParam,一些价值);
VAR的结果= _dbContext.SqlQuery<串GT;(SQL,someParamSqlParameter);
VAR containsAnyElements = result.Any();
所以,当调试器是在最后一行,当我尝试展开结果的结果查看它显示了我的期望结果(一些价值)
而是调用最后一行我得到了一个异常
它看起来像当我试图打开结果结果视图再次调用此查询。如果这种行为是否正确?如果是,请解释为什么发生这种情况。
It looks like when I try to open Result View of result it invokes this query again. If that behavior correct? If yes, please explain why that happens.
You're quite right - you're seeing the effects of Deferred Execution
Database.SqlQuery<T>
returns an IEnumerable<T>
which is actually an object of type:
System.Data.Entity.Internal.InternalSqlQuery<T>
So your result
object is actually just a description of the query - not the query results.
The SQL query is only actually executed on the database when you try to view the results of the query.
What you're seeing is this happening twice: once when your code calls .Any()
, and once when the debugger enumerates the result set.
You can fix this by explicitly telling EF when to run the query with .ToList()
:
var result = _dbContext.SqlQuery<string>(sql, someParamSqlParameter).ToList();
The type of result
is now List<string>
and it contains the results of your query.
这篇关于实体框架枚举类SqlQuery结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!