据我所知,Entity Framework实现了Identity Map Pattern,因此EF会在内存中缓存一些实体。
我举个例子。
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
有没有办法让第一个上下文的缓存无效并检索新的student
实体而不重新创建上下文?
感谢您的帮助。
答案 0 :(得分:19)
您必须强制EF重新加载实体。您可以为每个实体执行此操作:
context.Refresh(RefreshMode.StoreWins, student);
或者您可以进行查询:
ObjectQuery<Student> query = (ObjectQuery<Student>)context.Students.Where(st => st.Id == 34);
query.MergeOption = MergeOption.OverwriteChanges;
student = query.FirstOrDefault();
或在对象集上全局更改:
context.Students.MergeOption = MergeOption.OverwriteChanges;
答案 1 :(得分:8)
尝试刷新上下文:
context.Refresh(RefreshMode.StoreWins, yourObjectOrCollection);
因此,在您的情况下,您需要访问ObjectContext
var objContext = ((IObjectContextAdapter)this).ObjectContext;
刷新它:
objContext.Refresh(RefreshMode.StoreWins, anotherStudent);
此处有更多信息:http://msdn.microsoft.com/en-us/library/bb896255.aspx