Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing Data Using Entity Framework

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.

like image 255
chiefanov Avatar asked May 25 '11 15:05

chiefanov


People also ask

How do you refresh entities?

To refresh an entity definition: Right-click the Entities folder and select Refresh Entity.

How do I update a record in Entity Framework Core?

First, we create a new context and retrieve the existing department data from the database. We modify the Descr field. Since the context is open, it will mark the entity as Modified . Finally, when we call the SaveChanges , the context generates the update SQL statement to persist the change to the database.

How do you refresh an object in C#?

//Get the object Product someProduct = someObjectContext. Product. First(); //At runtime at some point, recreate the ObjectContext someObjectContext = new SomeObjectContext(); //Try to refresh someProduct on the new ObjectContext someObjectContext. Refresh(RefreshMode.


2 Answers

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();
like image 103
Ladislav Mrnka Avatar answered Oct 01 '22 12:10

Ladislav Mrnka


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.

like image 41
Nix Avatar answered Oct 01 '22 12:10

Nix