Using Entity Framework to Refresh Data



I'm attempting to query a database using Entity Framework, and I'm using the code below to obtain some data.

var students= MyEntities.Students.Where(s => s.Age > 20).ToList();

This code runs smoothly and provides accurate data. But if I run this code, then go to the database and alter the records to reflect the data this code should return, then run this code again without closing down the app, I receive the original data. It probably used to function well, but it no longer updates the data.

12/24/2012 10:42:55 PM

Accepted Answer

It didn't work, however. Identity mapping is a fundamental entity framework (and many ORM tool) function (clarification here).

Your entities won't be changed if you execute the query in the same context. Only newly generated entities that were added to the database between the two searches will be appended. You must take the following action to force EF to reload entities:

ObjectQuery query = MyEntities.Students;
query.MergeOption = MergeOption.OverwriteChanges;
var students = query.Where(s => s.Age > 20).ToList();
5/23/2017 11:44:11 AM

Popular Answer

Because EF caches data, if the data changes behind the scenes and you don't dispose of or reopen your context, you may have problems.

In order to avoid problems like the ones you just stated, the general rule of thumb is to limit the context's lifespan as brief as feasible.

Please remember what I indicated before, however you may use the Refresh() approach to force a refresh from the database.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow