[英]EF Core Transient DBContext get old value
我有一个瞬态 EF DB 上下文和一个瞬态服务。
I have a controller with an action using session service to update the session, and then use session service to query back the updated session.
但是,即使我使用瞬态,当我查询更新后的 session 时,session 仍然是旧值,但不是更新后的值。 有人可以回答为什么吗?
我的预期行为是,如果 DBContext 和 SessionService 是暂时的,在我更新后的 session 应该返回一个新的更新值而不是旧值。 因为 DBContext 应该在更新后被释放。
启动.cs
public void ConfigureServices(IServiceCollection services)
{
string connectionString = Configuration.GetConnectionString("ASPState");
services.AddDbContext<ASPStateContext>(options =>
options.UseSqlServer(connectionString, builder=> {
builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
}),ServiceLifetime.Transient);
services.AddTransient<ISessionService, SessionService>();
services.AddControllers();
}
SessionService.cs - 使用 DI
private ASPStateContext aspStateContext;
public SessionService(ASPStateContext dbContext)
{
aspStateContext = dbContext;
}
public async Task<IActionResult> UpdateSession(string id) {
await this.sessionService.UpdateSession(id);
var session = this.sessionService.GetSession(id); // return the value before update
}
ASPStateContext.cs
public partial class ASPStateContext : DbContext
{
public ASPStateContext()
{
}
我认为 Transient scope 的工作原理可能存在误解。 每次注入时都会实例化瞬态依赖项。 在您的 controller 中,瞬态和范围依赖的行为方式相同。 当另一个服务依赖于瞬态服务时,差异就出现了; 该其他服务将接收瞬态服务的新实例。
因此,您的 controller 将对整个请求使用相同的 SessionService(和相同的 EF 上下文)。
要确保实体框架从数据库中检索最新值,请使用AsNoTracking
查询扩展( 此处的文档)。 这将完全绕过 EF 缓存并查询底层数据库。
此外,请确保等待更新 session 数据后保存更改的 EF 调用。 否则,您的 SELECT 语句可能会在应用 UPDATE 语句之前执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.