8

Jak wiem Entity Framework implementuje Pattern mapy tożsamości, więc EF buforuje niektóre jednostki w pamięci.Jak unieważnić strukturę encji 4 Wewnętrzna pamięć podręczna

Pozwól, że dam ci przykład.

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 

Czy istnieje sposób, aby unieważnić cache Pierwszy kontekst i pobrać nowe student podmiot bez odtworzenie kontekstu?

Dzięki za pomoc.

Odpowiedz

19

Musisz wymusić EF, aby ponownie załadować encję. Można to zrobić albo za jednostki:

context.Refresh(RefreshMode.StoreWins, student); 

lub można to zrobić dla zapytania:

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

lub zmienić go na całym świecie obiektów zestawu:

context.Students.MergeOption = MergeOption.OverwriteChanges; 
8

odśwież kontekstu:

context.Refresh(RefreshMode.StoreWins, yourObjectOrCollection); 

Tak więc w twoim przypadku trzeba dostać się do ObjectContext

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

i odświeżyć go:

objContext.Refresh(RefreshMode.StoreWins, anotherStudent); 

Więcej informacji tutaj: http://msdn.microsoft.com/en-us/library/bb896255.aspx

Powiązane problemy