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

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

问题描述

我正在运行一些在一大堆实体上运行的更正代码,随着它的进展其速度降低,这是因为上下文中跟踪的实体数量随着每次迭代而增加,这可能需要很长时间,所以我正在保存更改在每次迭代结束时.每次迭代都是独立的,不会改变先前加载的实体.

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.

我知道我可以关闭更改跟踪,但我不想,因为它不是批量插入代码,而是加载实体并计算一些事情,如果数字不正确,请设置新数字并更新/删除/创建一些额外的实体.我知道我可以为每次迭代创建一个新的 DbContext 并且可能比在同一实例中执行所有操作运行得更快,但我认为可能有更好的方法.

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.

所以问题是;有没有办法清除之前在db上下文中加载的实体?

推荐答案

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

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;
}

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

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