How to invalidate entity framework 4 internal cache

Ivan Bianko picture Ivan Bianko · Mar 20, 2012 · Viewed 8.3k times · Source

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.

Answer

Ladislav Mrnka picture Ladislav Mrnka · Mar 20, 2012

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;