我最近重构了一个 WPF 应用程序,使其不再将 DbContext 的每次使用都包装在 using
中。子句(见 this question)。相反,我的应用程序始终使用相同的 DbContext 单例。
除了一个小问题外,这很好用。我有一个从头开始重建数据库并插入一些默认数据的例程。此例程直接使用 ADO.NET(不是 DbContext),因此 DbContext 不知道数据库现在完全不同。
有没有一种方法可以在不处理 DbContext 的情况下重置它?如果可能,我想避免处理,因为这会破坏整个应用程序中对原始单例的多个引用。
最佳答案
Entity Framework Core 5.0 现在有一个 ChangeTracker.Clear()
执行此操作的方法。如 the documentation 中所述,最好还是创建和处理DbContext
根据需要提供实例,但有时这是不切实际的。
DbContext
is designed to have a short lifetime where a new instance is created for each unit-of-work. This manner means all tracked entities are discarded when the context is disposed at the end of each unit-of-work. However, clearing all tracked entities using this method may be useful in situations where creating a new context instance is not practical.
关于entity-framework - 有没有办法在不处理和重新实例化 DbContext 的情况下重置它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643610/