8

据我所知实体框架实现了身份映射模式,因此EF缓存内存中的一些实体。如何使实体框架无效4内部缓存

让我给你举例。

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实体?

感谢您的帮助。

回答

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; 
8

尝试刷新背景:你需要去的ObjectContext的

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

并刷新

context.Refresh(RefreshMode.StoreWins, yourObjectOrCollection); 
你的情况

所以:

objContext.Refresh(RefreshMode.StoreWins, anotherStudent); 

此处了解详情:http://msdn.microsoft.com/en-us/library/bb896255.aspx