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

c# entity-framework-core

Question

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.

1
4
3/3/2016 1:55:48 PM

Accepted Answer

It does not matters if you have one, two or more instance of the same DbContext, the limitation of one datareader per connection 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"/>
9
10/23/2016 6:25:09 AM

Popular Answer

Consider that this may be a bug in the version you're using.

Without MultipleActiveResultSets active you can only have one DataReader per connection and nowhere in the code I can see more than one being used. It's very likely efcore is not closing it properly in ToListAsync() and enabling MARS is just masking the problem.

RTM has been released since your question was posted and your particular problem may very well be fixed already.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow