使用DbContext刷新实体实例

时间:2011-03-07 15:14:02

标签: entity-framework-4 entity-framework-ctp5 ef-code-first

使用EF4 CTP5 DbContext,相当于这个

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

我已经尝试了这个,但它没有做同样的事情,更新实例

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

3 个答案:

答案 0 :(得分:55)

你必须使用它:

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

答案 1 :(得分:23)

以上不起作用。 Reload()方法无法从数据库中正确刷新实体。它执行SQL选择查询,但不构建导航属性的代理。请参阅下面的示例(我使用带有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

答案 2 :(得分:0)

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

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

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