FirstOrDefault call in entity framework is cached but database is changed

血红的双手。 提交于 2020-01-02 06:50:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24340207/firstordefault-call-in-entity-framework-is-cached-but-database-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!