用DbContext刷新实体实例

与EF4 CTP5 DbContext,这是什么等效

public void Refresh(Document instance) { _ctx.Refresh(RefreshMode.StoreWins, instance); } 

我已经尝试过,但它不会做同样的事情,更新实例

  public void Refresh(Document instance) { _ctx.ChangeTracker.DetectChanges(); } 

你必须使用这个:

 public void Refresh(Document instance) { _ctx.Entry<Document>(instance).Reload(); } 

以上不起作用。 Reload()方法不能正确刷新数据库中的实体。 它执行SQL select查询,但不会为导航属性构build代理。 看下面的例子(我在EF 5.1中使用SQL Server中的Northwind数据库):

 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) 

我可以断定EF实体的刷新/重新加载可以通过Detach + Find来完成:

 ((IObjectContextAdapter)context).ObjectContext.Detach(entity); entity = context.<SomeEntitySet>.Find(entity.PrimaryKey); 

Nakov

我发现在具有导航属性的代理实体上重新加载失败。

作为一个解决办法,重置当前的值,然后像这样重新加载:

 var entry =_ctx.Entry<Document>(instance); entry.CurrentValues.SetValues(entry.OriginalValues); entry.Reload();