Guerrilla Guerrilla - 11 days ago 4x
C# Question

Quick way to set all flags in database?

I am looking for a quick way to set all flags in a table so I tried this:

using (var db = new PlaceDBContext())
Parallel.ForEach(db.Companies.Where(x => x.CheckedCompaniesHouse == true).ToList(),async (c) =>
c.CheckedCompaniesHouse = false;
await db.SaveChangesAsync();

But this doesn't work, its gives the error:

"A second operation started on this context before a previous
asynchronous operation completed. Use 'await' to ensure that any
asynchronous operations have completed before calling another method
on this context. Any instance members are not guaranteed to be thread

I am pretty sure I have done something very similar to this before and it worked fine. Can this approach work?

Is there a better way?


One of the best way to do what you are trying to achieve is using Entity Framework Extended Library:

    .Where(x => x.CheckedCompaniesHouse == true)
    .Update(t => new Company { CheckedCompaniesHouse = false });

Using this library you avoid the need to load the entities you want to modify into memory. The code I show above will be translated to a sql update batch.