FreeVice
FreeVice

Reputation: 2697

There is already an open DataReader

I have some code in my cshtml:

@model IEnumerable<Floor>
@{
    var floors = Model
}

And I have error in this line:

@foreach (var shopfloor in floor_l.ShopFloors)

I can get work around using .ToList() after Model assign.

What could be the cause of the error? who have faced?

This error appears sporadically.

Upvotes: 0

Views: 640

Answers (3)

bcr
bcr

Reputation: 2073

Be careful about lazy loading. If that's enabled, you can end up with this error if you're doing something in a loop, for example.

One way to get around this, if you don't want to turn off lazy loading (and have to remember to turn it back on again, if you need it) is to use eager loading, which you do by adding the Include() statement to your query. For example, if you have an entity called Contact and a reference to a collection of Address entities on a Contact and you want to get the Addresses for the Contacts you're querying for, using this in your LINQ query

.Include("Addresses")

and this will load the Addresses for each loaded Contact via the generated query. Use Include() sparingly on each query you want to use eager loading for though because there can be a performance hit.

Upvotes: 1

FreeVice
FreeVice

Reputation: 2697

"MultipleActiveResultSets=True" in connectionString

Upvotes: 0

Guffa
Guffa

Reputation: 700840

Each database connection can only support one data reader at a time. Your Model and foor_l are using the same connection, so you can only read from one of them at the same time.

Adding .ToList() will read all records from the data reader into a list, and close the data reader. That leaves the connection free to be used by the next data reader.

Upvotes: 1

Related Questions