实体框架中的FirstOrDefault调用被缓存,但数据库已更改 [英] FirstOrDefault call in entity framework is cached but database is changed
问题描述
我有以下电话:
var dbOrganisation = repository。 DbOrganisation.FirstOrDefault(c => c.Id == id);
我希望没有缓存这个电话。所以当我打电话时,我期望它查询数据库并检索最新的 DbOrganisation
对象。但是这不是发生了什么。
我相信这个方法相对较短的时间相对较短(〜5-10秒)。但是在这个时期,这个表中的十进制值可以由某些第三方更改。
但是,即使值更改, FirstOrDefault
呼叫检索未更新的版本。
示例情况:
- 我使用
FirstOrDefault
调用,并查看字段Credits的小数值
,是50 - 第三方将
信用
更改为45 - 我将$ 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:
- I make the
FirstOrDefault
call, and see the decimal value of the fieldCredits
, is 50 - A third party changes the
Credits
to 45 - I make the
FirstOrDefault
call 10 seconds, later, but theDbOrganisation
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屋!