作法:藉由保留資料庫值來解決衝突How to: Resolve Conflicts by Retaining Database Values

若要先協調預期和實際資料庫值之間的差異再重新送出變更,可以使用 OverwriteCurrentValues 將找到的值保留在資料庫中。To reconcile differences between expected and actual database values before you try to resubmit your changes, you can use OverwriteCurrentValues to retain the values found in the database. 這樣會覆寫物件模型 (Object Model) 中的目前值。The current values in the object model are then overwritten. 如需詳細資訊, 請參閱開放式平行存取:總覽For more information, see Optimistic Concurrency: Overview.

注意

在所有情況下,擷取資料庫中更新過的資料會先重新整理用戶端上的資料錄。In all cases, the record on the client is first refreshed by retrieving the updated data from the database. 這個動作可確保下一次嘗試更新時,不會在相同的並行存取檢查時失敗。This action makes sure that the next update try will not fail on the same concurrency checks.

範例Example

在這個案例下,當 User1 嘗試送出變更時,因為 User2 同時變更了 Assistant 和 Department 資料行,所以會擲回 ChangeConflictException 例外狀況。In this scenario, a ChangeConflictException exception is thrown when User1 tries to submit changes, because User2 has in the meantime changed the Assistant and Department columns. 下表顯示這個情況。The following table shows the situation.

主管Manager AssistantAssistant 部門Department
User1 和 User2 查詢時的原始資料庫狀態。Original database state when queried by User1 and User2. AlfredsAlfreds MariaMaria SalesSales
User1 準備送出這些變更。User1 prepares to submit these changes. AlfredAlfred 行銷Marketing
User2 已送出這些變更。User2 has already submitted these changes. MaryMary 服務Service

User1 決定讓較新的資料庫值覆寫物件模型中的目前值,來解決這個衝突。User1 decides to resolve this conflict by having the newer database values overwrite the current values in the object model.

User1 使用 OverwriteCurrentValues 解決衝突時,資料庫中的結果會如同下表:When User1 resolves the conflict by using OverwriteCurrentValues, the result in the database is as follows in the table:

主管Manager AssistantAssistant 部門Department
解決衝突後的新狀態。New state after conflict resolution. AlfredsAlfreds

(原始)(original)
MaryMary

(來自 User2)(from User2)
服務Service

(來自 User2)(from User2)

下列範例程式碼顯示如何使用資料庫值來覆寫物件模型中的目前值The following example code shows how to overwrite current values in the object model with the database values. (但不會對個別成員衝突進行任何檢查或自訂處理)。(No inspection or custom handling of individual member conflicts occurs.)

Northwnd db = new Northwnd("...");
try
{
    db.SubmitChanges(ConflictMode.ContinueOnConflict);
}

catch (ChangeConflictException e)
{
    Console.WriteLine(e.Message);
    foreach (ObjectChangeConflict occ in db.ChangeConflicts)
    {
        // All database values overwrite current values.
        occ.Resolve(RefreshMode.OverwriteCurrentValues);
    }
}
Dim db As New Northwnd("...")

Try
    db.SubmitChanges(ConflictMode.ContinueOnConflict)

Catch ex As ChangeConflictException
    Console.WriteLine(ex.Message)

    For Each occ As ObjectChangeConflict In db.ChangeConflicts
        ' All database values overwrite current values.
        occ.Resolve(Data.Linq.RefreshMode.OverwriteCurrentValues)
    Next

End Try

另請參閱See also