Iva*_*nko 8 .net caching entity-framework identity-map entity-framework-4
据我所知,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
Run Code Online (Sandbox Code Playgroud)
有没有办法使第一个上下文的缓存无效并检索新student实体而无需重新创建上下文?
感谢帮助.
Lad*_*nka 19
您必须强制EF重新加载实体.您可以为每个实体执行此操作:
context.Refresh(RefreshMode.StoreWins, student);
Run Code Online (Sandbox Code Playgroud)
或者您可以进行查询:
ObjectQuery<Student> query = (ObjectQuery<Student>)context.Students.Where(st => st.Id == 34);
query.MergeOption = MergeOption.OverwriteChanges;
student = query.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
或者在对象集上全局更改它:
context.Students.MergeOption = MergeOption.OverwriteChanges;
Run Code Online (Sandbox Code Playgroud)
尝试刷新上下文:
context.Refresh(RefreshMode.StoreWins, yourObjectOrCollection);
Run Code Online (Sandbox Code Playgroud)
因此,在您的情况下,您需要访问ObjectContext
var objContext = ((IObjectContextAdapter)this).ObjectContext;
Run Code Online (Sandbox Code Playgroud)
并刷新它:
objContext.Refresh(RefreshMode.StoreWins, anotherStudent);
Run Code Online (Sandbox Code Playgroud)
更多信息:http://msdn.microsoft.com/en-us/library/bb896255.aspx
| 归档时间: |
|
| 查看次数: |
8181 次 |
| 最近记录: |