实体框架中的FirstOrDefault调用被缓存,但数据库已更改 [英] FirstOrDefault call in entity framework is cached but database is changed

查看:204
本文介绍了实体框架中的FirstOrDefault调用被缓存,但数据库已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,我以前没有经历过。我使用实体框架来检索我的记录。



我有以下电话:

  var dbOrganisation = repository。 DbOrganisation.FirstOrDefault(c => c.Id == id); 

我希望没有缓存这个电话。所以当我打电话时,我期望它查询数据库并检索最新的 DbOrganisation 对象。但是这不是发生了什么。



我相信这个方法相对较短的时间相对较短(〜5-10秒)。但是在这个时期,这个表中的十进制值可以由某些第三方更改。



但是,即使值更改, FirstOrDefault 呼叫检索未更新的版本。



示例情况


  1. 我使用 FirstOrDefault 调用,并查看字段 Credits的小数值,是50

  2. 第三方将信用更改为45

  3. 我将$ code> FirstOrDefault 通话10秒钟,但是$ DbOrganisation 仍然有50美元的信用

我做错了什么?我认为默认情况下没有缓存 FirstOrDefault 调用?

解决方案

你做一切正确,这就是EF的工作原理。



您可以使用 .AsNoTracking()为您的目的: / p>

  var dbOrganisation = repository.DbOrganisation.AsNoTracking()。FirstOrDefault(c => c.Id == id); 

DbExtensions.AsNoTracking方法:返回一个新的查询,其中返回的实体将不会缓存在DbContext或ObjectContext中。


I have a strange issue, which I haven't experienced before. I use Entity Framework to retrieve my records.

I have the following call:

 var dbOrganisation = repository.DbOrganisation.FirstOrDefault(c => c.Id == id);

I expect no caching of this call. So when I make this call, I expect it to query the database and retrieve the latest DbOrganisation object. But that is not what happens.

I call this method relatively two times relatively short time after eachother (~5-10 seconds). But in this period, a decimal value in this table, can be changed by some third party.

However, even though the value changes, the FirstOrDefault call retrieves the not updated version.

Example situation:

  1. I make the FirstOrDefault call, and see the decimal value of the field Credits, is 50
  2. A third party changes the Credits to 45
  3. I make the FirstOrDefault call 10 seconds, later, but the DbOrganisation still have 50 in Credits

What am i doing wrong? I thought the FirstOrDefault call was not cached by default?

解决方案

You doing everything correct, that's just how EF works.

You can use .AsNoTracking() for you purposes:

var dbOrganisation = repository.DbOrganisation.AsNoTracking().FirstOrDefault(c => c.Id == id);

DbExtensions.AsNoTracking Method: Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext.

这篇关于实体框架中的FirstOrDefault调用被缓存,但数据库已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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