使用DbContext刷新实体实例

mar*_*are 40 entity-framework-4 ef-code-first entity-framework-ctp5

使用EF4 CTP5 DbContext,相当于此

    public void Refresh(Document instance)
    {
        _ctx.Refresh(RefreshMode.StoreWins, instance);
    }
Run Code Online (Sandbox Code Playgroud)

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

    public void Refresh(Document instance)
    {
        _ctx.ChangeTracker.DetectChanges();
    }
Run Code Online (Sandbox Code Playgroud)

Lad*_*nka 56

你必须使用这个:

public void Refresh(Document instance)
{
  _ctx.Entry<Document>(instance).Reload();
}
Run Code Online (Sandbox Code Playgroud)


Sve*_*kov 24

以上不起作用.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)
Run Code Online (Sandbox Code Playgroud)

我可以得出结论,EF实体的真正刷新/重载可以通过Detach + Find来完成:

((IObjectContextAdapter)context).ObjectContext.Detach(entity);
entity = context.<SomeEntitySet>.Find(entity.PrimaryKey);
Run Code Online (Sandbox Code Playgroud)

Nakov

  • 来自@ Dimitar-Dimitrov的NAA:`你使用POCO类的构造函数来创建一个新的Product对象,因此它不会是代理.您应该使用DbSet.Create方法来获取代理.当您从上下文中分离实体并使用Find方法从数据库加载它时,Entity Framework将为该实体创建一个代理.这就是它与Detach + Find一起使用的原因.但是,DbEntityEntry.Reload方法不会刷新实体的关系 (8认同)