Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework returns stale data when selecting the whole entity but up to date when selecting just a field

My Entity Framework backed project returns stale data when selecting the whole entity but the data is up to date when selecting just a field from the entity.

Here are the steps:

  1. Query via EF/LINQ:

    var e  = context.myEntity.First(x=>x.ID==ID);
    string n = context.myEntity.Where(x=>x.ID==ID).Select(x=>x.Name).First();
    
  2. Update the Name field in the DB via SQL directly

  3. Then Query again via EF/LINQ:

    var e  = context.myEntity.First(x=>x.ID==ID);
    string n = context.myEntity.Where(x=>x.ID==ID).Select(x=>x.Name).First();
    

e.Name is the previous value but n is up to date.

We are re-using the same context between calls.

Using the SQL profiler, I can confirm that even when the data is stale the SQL query from EF occurs.

What can cause this?

like image 713
Matt Avatar asked Aug 31 '25 11:08

Matt


1 Answers

The data is cached in the Context. Ideally your context should have a short lifetime (a unit of work, for example) to prevent this behaviour becoming a problem, but if you need to force an update from the database, set the MergeOption to OverwriteChanges

context.MergeOption = MergeOption.OverwriteChanges
like image 88
podiluska Avatar answered Sep 02 '25 23:09

podiluska