Как применить изменения, выполненные в отсоединенном объекте (платформа Entity Framework)

В этом разделе приведен пример того, как применить к объекту обновления, выполненные в отсоединенном экземпляре того же объекта. Эта процедура используется, если объект обновляется отдельно, а затем возвращается на сервер для сохранения изменений. Если объект будет просто присоединен к контексту объекта на сервере, то обновления окажутся потерянными или операция окончится неудачей при условии, что объект уже находился в контексте объекта. Это происходит, поскольку объекты присоединяются в состоянии Unchanged. Дополнительные сведения см. в разделе Присоединение и отсоединение объектов (платформа Entity Framework).

Пример в этом разделе основан на модели Adventure Works Sales. Чтобы запустить код из данного примера, нужно сначала добавить к проекту модель AdventureWorks Sales и настроить его для использования платформы Entity Framework. Для этого выполните инструкции из разделов Как вручную настроить проект Entity Framework и Как определить модель и файлы сопоставления вручную (платформа Entity Framework).

Пример

В следующем примере обновленный объект SalesOrderDetail передается методу UpdateItemChanges наряду с первоначальным объектом. Это дает возможность применить изменения без запроса объекта и без необходимости его сохранения в памяти. Можно также извлечь исходный объект из базы данных, не требуя его передачи от клиента.

Private Shared Sub ApplyItemUpdates(ByVal originalItem As SalesOrderDetail, ByVal updatedItem As SalesOrderDetail)
    Using context As New AdventureWorksEntities()
        context.SalesOrderDetails.Attach(updatedItem)
        ' Check if the ID is 0, if it is the item is new. 
        ' In this case we need to chage the state to Added. 
        If updatedItem.SalesOrderDetailID = 0 Then
            ' Because the ID is generated by the database we do not need to 
            ' set updatedItem.SalesOrderDetailID. 
            context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added)
        Else
            ' If the SalesOrderDetailID is not 0, then the item is not new 
            ' and needs to be updated. Because we already added the 
            ' updated object to the context we need to apply the original values. 
            ' If we attached originalItem to the context 
            ' we would need to apply the current values: 
            ' context.ApplyCurrentValues("SalesOrderDetails", updatedItem); 
            ' Applying current or original values, changes the state 
            ' of the attached object to Modified. 
            context.ApplyOriginalValues("SalesOrderDetails", originalItem)
        End If
        context.SaveChanges()
    End Using
End Sub
private static void ApplyItemUpdates(SalesOrderDetail originalItem,
    SalesOrderDetail updatedItem)
{
    using (AdventureWorksEntities context =
        new AdventureWorksEntities())
    {
        context.SalesOrderDetails.Attach(updatedItem);
        // Check if the ID is 0, if it is the item is new. 
        // In this case we need to chage the state to Added.
        if (updatedItem.SalesOrderDetailID == 0)
        {
            // Because the ID is generated by the database we do not need to
            // set updatedItem.SalesOrderDetailID.
            context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
        }
        else
        {
            // If the SalesOrderDetailID is not 0, then the item is not new
            // and needs to be updated. Because we already added the 
            // updated object to the context we need to apply the original values.
            // If we attached originalItem to the context 
            // we would need to apply the current values:
            // context.ApplyCurrentValues("SalesOrderDetails", updatedItem);
            // Applying current or original values, changes the state 
            // of the attached object to Modified.
            context.ApplyOriginalValues("SalesOrderDetails", originalItem);
        }
        context.SaveChanges();
    }
}

См. также

Основные понятия

Построение многоуровневых приложений (платформа Entity Framework)
Сериализация объектов (платформа Entity Framework)
Присоединение и отсоединение объектов (платформа Entity Framework)
Работа с объектами (платформа Entity Framework)