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:
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();
Update the Name field in the DB via SQL directly
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With