AsValeO AsValeO - 1 month ago 7
C# Question

Entity Framework 7 (Core): DataReader must be closed exception

I'm using EF7 (EF Core).
When I'm trying to update DB items like this in single method...

using (var db = new DBContext())
{
var deadSources =
await
db.Source.Where(x => !x.Item.Any())
.ToListAsync();
foreach (var srs in deadSources)
{
srs.InspectionFailed = true;
srs.InspectionFailedDescription = "ERROR";
}
await db.SaveChangesAsync();
}

using (var db = new DBContext())
{
var aliveSources =
await
db.Source.Where(x => x.Item.Any())
.ToListAsync();
foreach (var srs in aliveSources)
{
srs.InspectionFailed = false;
srs.InspectionFailedDescription = string.Empty;
}
await db.SaveChangesAsync(); // Exception here
}


... this exception is thrown:


There is already an open DataReader associated with this Command which
must be closed first.


How can I avoid this? There are two different contexts for each DB request so I can't get why this happens.

Answer

It does not matters if you have one, two or more instance of the same DbContext, the limitation of one datareader per application exists in database service side, so you need to enable MultipleActiveResultSets option in your connection string:

<add name="XYZ" connectionString="Server=SERVER;Database=DATABASE;
 Trusted_Connection=SSPI;MultipleActiveResultSets=True;"
 providerName="System.Data.SqlClient"/>