I'm trying to use Entity Framework to query database and I have following code that I'm using to get some data.
var students= MyEntities.Students.Where(s => s.Age > 20).ToList();
This code works fine and returns correct data. However, if I run this code, then go to database and update records to change the data this code should return, and then re-run this code without shutting down the app, I'm getting original data. I'm pretty sure it used to work fine, but now this doesn't refresh data.
No it never worked. This is essential behavior of entity framework (and many ORM tools) called identity map (explanation here).
If you run the query on the same context you will not get your entities updated. It will only append new entities created in the database between running those two queries. If you want to force EF to reload entities you must do something like this:
ObjectQuery query = MyEntities.Students; query.MergeOption = MergeOption.OverwriteChanges; var students = query.Where(s => s.Age > 20).ToList();
You are running into issues because EF caches data, so if the data changes behind the scenes, and you dont dispose/reopen your context you are going to run into issues.
The general rule of thumb is to keep the lifetime of the context as short as possible, to circumvent issues like you just mentioned.
Please do not disregard what I said above, but if you would like to force a refresh from the DB you could use the Refresh() method.