如何刷新实体框架核心DBContext? [英] How to refresh an Entity Framework Core DBContext?

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

问题描述

当我的表被另一方更新时,dotnet核心中的db上下文仍然返回旧值,如何强制Db上下文刷新?

When my table is updated by another party, the db context in dotnet core still return the old value, how can I force the Db context to refresh?

I已经做过研究,但我只发现人们使用 Reload 方法(在EF核心中不可用)来强制刷新上下文。

I've done research but I only found people use Reload method, which is not available in EF core, to force the context to refresh.

其他一些解决方案建议在使用后处置上下文,但是我收到错误消息,说数据库上下文是由依赖注入创建的,我不应该弄乱它。

Some other solution suggests dispose the context after using, but I get error saying the DB context is created by dependency injection and I should not mess up with it.

推荐答案

依赖注入和DbContext



您提到在尝试重新创建 DbContext ,您会收到有关由依赖项注入(DI)系统管理的上下文的错误。使用依赖项注入系统创建对象有两种不同的样式。 DI可以创建一个在所有使用者之间共享的服务的全局单例实例,也可以按工作范围/单位(例如,Web服务器中的每个请求)创建一个实例。

Dependency Injection and DbContext

You mention that when you try to recreate your DbContext, you get an error about the context being managed by your dependency injection (DI) system. There are two different styles of using a dependency injection system for object creation. The DI can either create a global singleton instance that is shared as a service between all consumers or it can create an instance per scope/unit of work (e.g., per request in a web server).

如果将DI系统配置为创建 DbContext 的单个全局共享实例,那么您将遇到与寿命长的<$ c $相关的各种问题c> DbContext

If your DI system is configured to create a single global shared instance of DbContext, then you will encounter various problems associated with long-lived DbContext.


  • DbContext ,通过设计,永远不要自动从其缓存中删除对象,因为它的目的不是长期存在。因此,寿命长的 DbContext 将浪费内存。

  • 您的代码将永远不会看到对加载到其缓存中的项目所做的更改,而无需手动进行重新加载它加载的每个实体。

  • DbContext 只允许一个查询随时运行,并且不是线程安全的。如果您尝试在一个全局共享实例上运行多个查询,它将抛出 DbConcurrencyException (至少在其异步接口上,不确定其同步接口)。

  • DbContext, by design, never automatically removes objects from its cache because it is not designed to be long-lived. Thus, a long-lived DbContext will retain memory wastefully.
  • Your code will never see changes to items loaded into its cache without manually reloading each entity it loads.
  • DbContext only allows one query to run at any time and is not threadsafe. If you try to run multiple queries on a globally shared instance, it will throw DbConcurrencyException (at least on its async interface, not sure about its sync interface).

因此,最佳做法是每个工作单元使用单个 DbContext 。您的DI系统可以通过配置为在范围内为您的应用程序处理的每个请求提供一个新实例来帮助您。例如,ASP.NET Core的依赖注入系统支持按请求对实例进行范围界定。

Thus, the best practice is to use a single DbContext per unit of work. Your DI system can help you with this by being configured to provide a fresh instance for each request your application processes within a scope. For example, ASP.NET Core’s Dependency Injection system supports scoping instances by request.

获取最新数据的最简单方法是创建一个新的 DbContext 。但是,在您的工作单元中,或在DI系统提供的范围界定的范围内,您可能会触发一个外部过程,该过程应该直接在数据库中修改您的实体。您可能需要先看到所做的更改,然后才能退出DI的范围或完成工作单元。在这种情况下,您可以通过分离数据对象的实例来强制重新加载。

The easiest way to get fresh data is to create a new DbContext. However, within your unit of work, or within the constraints of the granularity of scoping provided by your DI system, you may trigger an external process which is supposed to modify your entity directly in the database. You may need to see that change before exiting your DI’s scope or completing your unit of work. In that case, you can force a reload by detaching your instance of the data object.

为此,请首先获取 EntityEntry<> 你的对象。该对象使您可以为该对象操纵 DbContext 的内部缓存。然后,可以通过将 EntitytState.Detached 分配给其 State 属性,将其标记为分离。我相信这会将条目保留在缓存中,但会导致 DbContext 在以后实际加载条目时删除并替换它。重要的是,这会导致将来的负载将新加载的实体实例返回到您的代码。例如:

To do this, first get the EntityEntry<> for your object. This is an object which lets you manipulate DbContext’s internal cache for that object. You can then mark this entry detached by assigning EntitytState.Detached to its State property. I believe that this leaves the entry in the cache but causes the DbContext to remove and replace it when you actually load the entry in the future. What matters is that it causes a future load to return a freshly loaded entity instance to your code. For example:

var thing = context.Things.Find(id);
if (thing.ShouldBeSentToService) {
    TriggerExternalServiceAndWait(id);

    // Detach the object to remove it from context’s cache.
    context.Entities(thing).State = EntityState.Detached;

    // Then load it. We will get a new object with data
    // freshly loaded from the database.
    thing = context.Things.Find(id);
}
UseSomeOtherData(thing.DataWhichWasUpdated);

这篇关于如何刷新实体框架核心DBContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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