Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear tracked entities in entity framework

I am running some correction code that runs over a big pile of entities, as it progress its speed decreases, that is because the number of tracked entities in the context increase with each iteration, It can take long so I am saving changes at the end of each iteration. Each iteration is independent and does not change the previosuly loaded entities.

I know I can turn off change tracking but I do not want to, because it is not a bulk insert code, but loading the entities and calculating a few things and if the numbers are not correct set the new numbers and update/delete/create some additional entities. I know I can create a new DbContext for each iteration and probably that would run faster than doing all in the same instance, but I am thinking that there might be a better way.

So the question is; Is there a way of clearing the entities previously loaded in the db context?

like image 386
hazimdikenli Avatar asked Dec 11 '14 12:12

hazimdikenli


People also ask

How do I delete data in Entity Framework?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.

What does AsNoTracking do in Entity Framework?

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query.

How do I turn off change tracking in Entity Framework?

In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.

How do you refresh entity?

The best way to refresh entities in your context is to dispose your context and create a new one.


1 Answers

You can add a method to your DbContext or an extension method that uses the ChangeTracker to detach all the Added, Modified, and Deleted entities:

public void DetachAllEntities() {     var changedEntriesCopy = this.ChangeTracker.Entries()         .Where(e => e.State == EntityState.Added ||                     e.State == EntityState.Modified ||                     e.State == EntityState.Deleted)         .ToList();      foreach (var entry in changedEntriesCopy)         entry.State = EntityState.Detached; } 
like image 51
David Sherret Avatar answered Nov 05 '22 20:11

David Sherret