0

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!

Ydhem
  • 928
  • 2
  • 14
  • 36

1 Answers1

0

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
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I have changed the source of the `Controller` to the such code: http://ideone.com/jE6Ps1 and data is binding pretty fine without exceptions. Thanks for the advice, Marc, but I think the new code does look very ugly :( Is an Entity Model so whimsical? –  Jun 30 '13 at 14:40