且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在实体框架中清除跟踪的实体

更新时间:2023-02-04 19:11:01

您可以添加一个方法您的 DbContext 或使用ChangeTracker分离所有添加,修改和删除的实体的扩展方法:

  public void DetachAllEntities()
{
var changedEntriesCopy = this.ChangeTracker.Entries()
.Where(e => e.State == EntityState 。添加||
e.State == EntityState.Modified ||
e.State == EntityState.Deleted)
.ToList();
foreach(changeEntriesCopy中的var entity)
{
this.Entry(entity.Entity).State = EntityState.Detached;
}
}


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?

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 entity in changedEntriesCopy)
    {
        this.Entry(entity.Entity).State = EntityState.Detached;
    }
}