سؤال

I'm using ADO.NET Entity model for data binding and other data manipulation for my ASP.NET MVC 4 Razor project.

I'm trying, in my model, to bind data like this in my Controller:

http://ideone.com/GvskaG

When I reach the line 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."}

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.

I think, that it could be because of 15-th line:

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.

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? That is the usual way of causing this - foreaching over the first reader while doing an n+1 (query per item) inside the loop. 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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top