简体   繁体   English

ASP.NET MVC项目中已为ADO.NET实体模型打开的DataReader

[英]An already open DataReader for the ADO.NET Entity model in ASP.NET MVC project

I'm using ADO.NET Entity model for data binding and other data manipulation for my ASP.NET MVC 4 Razor project. 我将ADO.NET实体模型用于ASP.NET MVC 4 Razor项目的数据绑定和其他数据处理。

I'm trying, in my model, to bind data like this in my Controller : 我正在我的模型中尝试在Controller像这样绑定数据:

http://ideone.com/GvskaG http://ideone.com/GvskaG

When I reach the line 26: 当我到达第26行时:

26. Sender = db.GetLoginByUserId(item.sender_id).FirstOrDefault(),
27. Receiver = db.GetLoginByUserId(item.recv_id).FirstOrDefault(),

I'm getting such an error: 我收到这样的错误:

{"There is already an open DataReader associated with this Connection which must be closed first."} {“已经有与此连接关联的打开的DataReader,必须首先关闭它。”}

Really, I don't understand how to close it manually, because ADO.NET Entity is too automatic, and I didn't define any opening are closing for the DataReader or connection. 真的,我不知道如何手动关闭它,因为ADO.NET实体太自动了,而且我也没有定义DataReader或连接的任何打开都在关闭。

I think, that it could be because of 15-th line: 我认为这可能是由于第15行:

15. var currentUserId = db.GetUserIdByLogin(Request.Cookies["user-name"].Value);

And the Entity model does open the connection/DataReader and removing them only after brace } symbol, when GC is collectiing the garbage. 当GC收集垃圾时,实体模型确实会打开连接/ DataReader并仅在大括号}之后删除它们。

It looks like I can make only one call in the single method, but if I want more calls from Entity model, how could it be done? 看起来我只能在一个方法中进行一次调用,但是如果我想从实体模型中进行更多调用,该怎么办?

Thanks! 谢谢!

Are you perhaps in a foreach loop at this point? 您现在是否处于foreach循环中? That is the usual way of causing this - foreaching over the first reader while doing an n+1 (query per item) inside the loop. 这是导致这种情况的常用方法-在循环内执行n + 1(每个项目的查询)时在第一个阅读器上进行遍历。 The usual fixes are (one of): 通常的解决方法是(以下一项):

  • configure the query to eagerly fetch the nested data so that it is already available 配置查询以急切地获取嵌套数据,以便它已经可用
  • buffer the outer loop into a list/array, so that the reader is finished before the inner loop starts 将外部循环缓冲到列表/数组中,以便读取器在内部循环开始之前完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM