Подтвердить что ты не робот

Обновить экземпляр объекта с помощью DbContext

С EF4 CTP5 DbContext, что эквивалентно этому

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

Я пробовал это, но он не делает то же самое, обновляя экземпляр

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

?

4b9b3361

Ответ 1

Вы должны использовать это:

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

Ответ 2

Вышеуказанное не работает. Метод Reload() неправильно обновляет объект из базы данных. Он выполняет запрос выбора SQL, но не создает прокси для навигационных свойств. См. Пример ниже (я использую базу данных Northwind в SQL Server с 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 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);

Нак

Ответ 3

Я обнаружил, что перезагрузка завершилась неудачей с прокси-сущностями, обладающими свойствами навигации.

Как работа, reset текущие значения, а затем перезагрузите вот так:

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