Was ist das mit EF4 CTP5 DbContext?
public void Refresh(Document instance)
{
_ctx.Refresh(RefreshMode.StoreWins, instance);
}
Ich habe es versucht, aber es tut nicht dasselbe, die Instanz wird aktualisiert
public void Refresh(Document instance)
{
_ctx.ChangeTracker.DetectChanges();
}
?
Sie müssen dies verwenden:
public void Refresh(Document instance)
{
_ctx.Entry<Document>(instance).Reload();
}
Das obige funktioniert nicht. Die Reload () -Methode aktualisiert die Entität aus der Datenbank nicht korrekt. Es führt eine SQL-Auswahlabfrage aus, erstellt jedoch keine Proxys für die Navigationseigenschaften. Siehe das folgende Beispiel (Ich verwende die Northwind-Datenbank in SQL Server mit EF 5.1):
NorthwindEntities northwindEntities = new NorthwindEntities();
Product newProduct = new Product
{
ProductName = "new product",
Discontinued = false,
CategoryID = 3
};
northwindEntities.Products.Add(newProduct);
northwindEntities.SaveChanges();
// Now the product is stored in the database. Let's print its category
Console.WriteLine(newProduct.Category); // prints "null" -> navigational property not loaded
// Find the product by primary key --> returns the same object (unmodified)
// Still prints "null" (due to caching and identity resolution)
var productByPK = northwindEntities.Products.Find(newProduct.ProductID);
Console.WriteLine(productByPK.Category); // null (due to caching)
// Reloading the entity from the database doesn't help!
northwindEntities.Entry<Product>(newProduct).Reload();
Console.WriteLine(newProduct.Category); // null (reload doesn't help)
// Detach the object from the context
((IObjectContextAdapter)northwindEntities).ObjectContext.Detach(newProduct);
// Now find the product by primary key (detached entities are not cached)
var detachedProductByPK = northwindEntities.Products.Find(newProduct.ProductID);
Console.WriteLine(detachedProductByPK.Category); // works (no caching)
Ich kann daraus schließen, dass das eigentliche Aktualisieren/Neuladen der EF-Entität mit Detach + Find ausgeführt werden kann:
((IObjectContextAdapter)context).ObjectContext.Detach(entity);
entity = context.<SomeEntitySet>.Find(entity.PrimaryKey);
Nakov
Ich habe festgestellt, dass das Neuladen auf Proxy-Entitäten mit Navigationseigenschaften fehlschlägt.
Setzen Sie die aktuellen Werte zurück und laden Sie sie anschließend wie folgt zurück:
var entry =_ctx.Entry<Document>(instance);
entry.CurrentValues.SetValues(entry.OriginalValues);
entry.Reload();