Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
AsValeO Avatar asked Dec 18 '22 19:12

AsValeO


1 Answers

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"/>
like image 109
E-Bat Avatar answered Dec 29 '22 07:12

E-Bat