实体框架枚举类SqlQuery结果 [英] Entity Framework enumerating SqlQuery result

查看:160
本文介绍了实体框架枚举类SqlQuery结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有奇怪的错误,当我试图查看SqlQuery类的结果:

  VAR SQL =SELECT @someParam 
变种someParamSqlParameter =新的SqlParameter(someParam,一些价值);
VAR的结果= _dbContext.SqlQuery<串GT;(SQL,someParamSqlParameter);
VAR containsAnyElements = result.Any();



所以,当调试器是在最后一行,当我尝试展开结果的结果查看它显示了我的期望结果(一些价值)而是调用最后一行我得到了一个异常



<块引用>

SqlParameter有已被另一
SqlParameterCollection载。




它看起来像当我试图打开结果结果视图再次调用此查询。如果这种行为是否正确?如果是,请解释为什么发生这种情况。


解决方案

它看起来像当我尝试打开的结果结果查看再次调用此查询




您说得很对 - 你看到的 延迟执行



Database.SqlQuery< T> 返回的IEnumerable< T> 这实际上是一个类型的对象:

  System.Data.Entity.Internal.InternalSqlQuery< T> 



所以你的结果对象实际上仅仅是一个查询的说明 - 不是查询结果。



在SQL查询实际上只当您尝试查看查询结果的数据库上执行



你看到的是这样的情况发生了两次:一次是当你的代码调用。任何(),调试器枚举一次,结果集。






您可以通过在运行具有查询明确地告诉EF解决这个问题.ToList()

  VAR的结果= _dbContext.SqlQuery<串>(SQL,someParamSqlParameter) .ToList(); 



类型的结果现在列表与LT;字符串方式> ,它包含您的查询的结果。


I have strange error while I am trying to view results of SqlQuery:

var sql = "SELECT @someParam";
var someParamSqlParameter = new SqlParameter("someParam", "Some Value");
var result = _dbContext.SqlQuery<string>(sql, someParamSqlParameter);
var containsAnyElements = result.Any();

So when debugger is at last line and when I try to expand Results View of result it shows me expected result("Some Value") but on invoking last line I got an exception

"The SqlParameter is already contained by another SqlParameterCollection.".

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.

解决方案

It looks like when I try to open Result View of result it invokes this query again

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结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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