如何在实体框架中清除跟踪的实体 [英] How do I clear tracked entities in entity framework

查看:157
本文介绍了如何在实体框架中清除跟踪的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一些修正代码,运行在一大堆实体上,因为它的速度降低,这是因为跟踪的实体数量在每个迭代中增加,可能需要很长时间才能保存更改在每次迭代结束时。每次迭代都是独立的,不会改变先前加载的实体。



我知道我可以关闭更改跟踪,但我不想,因为它不是大量插入代码,而是加载实体并计算一些事情,如果数字不正确设置新数字并更新/删除/创建一些其他实体。我知道我可以为每次迭代创建一个新的DbContext,可能运行速度比在同一个实例中执行的要快,但我认为可能会有更好的方法。



所以问题是有没有办法清除先前在数据库上下文中加载的实体?

解决方案

您可以添加一个方法您的 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;
    }
}

这篇关于如何在实体框架中清除跟踪的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆