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.
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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With