Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invalidate entity framework 4 internal cache

As I know Entity Framework implements the Identity Map Pattern, so EF caches some entities in the memory.

Let I give you example.

var context = new StudentContext();

var student = context.Students.Where(st => st.Id == 34).FirstOrDefault();

// any way of changing student in DB
var anotherContext = new StudentContext();
var anotherStudent = anotherContext.Students.Where(st => st.Id == 34).FirstOrDefault();
anotherStudent.Name = "John Smith";
anotherContext.SaveChanges();

student = context.Students.Where(st => st.Id == 34).FirstOrDefault();
// student.Name contains old value   

Is there a way to invalidate first context's cache and retrieve new student entity without recreating context?

Thanks for help.

like image 638
Ivan Bianko Avatar asked Mar 20 '12 10:03

Ivan Bianko


People also ask

Does Entity Framework cache data?

Entity Framework has the following forms of caching built-in: Object caching – the ObjectStateManager built into an ObjectContext instance keeps track in memory of the objects that have been retrieved using that instance. This is also known as first-level cache.

Does EF cache result?

Caching with Entity Framework NCache introduces the caching provider which acts between Entity Framework and the Data source. The major reason behind the EF Caching provider is to reduce database trips (which slow down application performance) and serve the query result from the cache.


2 Answers

You must force EF to reload the entity. You can either do that per entity:

context.Refresh(RefreshMode.StoreWins, student);

or you can do it for query:

ObjectQuery<Student> query = (ObjectQuery<Student>)context.Students.Where(st => st.Id == 34);
query.MergeOption = MergeOption.OverwriteChanges;
student = query.FirstOrDefault();

or change it globally on object set:

context.Students.MergeOption = MergeOption.OverwriteChanges;
like image 152
Ladislav Mrnka Avatar answered Oct 09 '22 06:10

Ladislav Mrnka


try refreshing the context:

context.Refresh(RefreshMode.StoreWins, yourObjectOrCollection);

So in your case you need to get to the ObjectContext

var objContext = ((IObjectContextAdapter)this).ObjectContext;

And refresh it:

objContext.Refresh(RefreshMode.StoreWins, anotherStudent);

More info here : http://msdn.microsoft.com/en-us/library/bb896255.aspx

like image 8
Giorgio Minardi Avatar answered Oct 09 '22 05:10

Giorgio Minardi