How do I clear tracked entities in entity framework

c# 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?

12/11/2014 1:15:24 PM

Accepted Answer

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)

    foreach (var entry in changedEntriesCopy)
        entry.State = EntityState.Detached;
8/28/2018 1:05:48 PM

Popular Answer

1. Possibility: detach the entry

dbContext.Entry(entity).State = EntityState.Detached;

When you detach the entry the change tracker will stop tracking it (and should result in better performance)


2. Possibility: work with your own Status field + disconnected contexts

Maybe you want to control the status of your entity independently so you can use disconnected graphs. Add a property for the entity status and transform this status into the dbContext.Entry(entity).State when performing operations (use a repository to do this)

public class Foo
    public EntityStatus EntityStatus { get; set; }

public enum EntityStatus

See following link for an example:

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow