简体   繁体   中英

Fastest way to set state to modified for entity in entity framework\sqlite

I have a large number of entities for example 10k entities that have all been updated. I need a fast way to change the state and ultimately commit them to the database.

BaseOtiveContext.Entry(Entity).State = EntityState.Modified;

For bulk inserts I can easily achieve very fast results with add range.

BaseOtiveContext.Contacts.AddRange(Entities)

I tried parallel for each for the updated entities but it throws an error as the object in the collection is modified.

I need a way to do this:

BaseOtiveContext.Contacts.AddRange(Entities)

but at the same time change the state to

   .State = EntityState.Modified;

Solved my issues the following way:

      using (DbContextTransaction txUpdate = dbUpdate.Database.BeginTransaction())
        {
            dbUpdate.Configuration.AutoDetectChangesEnabled = false;
            foreach(var Item in UpdateItems)
            {
                dbUpdate.Entry<V2Contact>(Item).State = EntityState.Modified;
            }
            dbUpdate.Configuration.AutoDetectChangesEnabled = true;
            dbUpdate.ChangeTracker.DetectChanges();
            dbUpdate.SaveChanges();
            txUpdate.Commit();
        }

The first thing is to disable change tracking, then change the state of each object to update. The change state operation will happen quickly as change tracking is disabled, once done turn it back on and finally call detect changes, save and commit

The number of optimal parallel threads count (N) depends mostly on your CPU. Split the collection of objects into (N) groups so then each thread will process only objects belonging to it. When all threads complete, call Commit (SaveChanges).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM