HOW TO:藉由覆寫資料庫值來解決衝突How to: Resolve Conflicts by Overwriting Database Values

若要先協調預期和實際資料庫值之間的差異再重新送出變更,可以使用 KeepCurrentValues 覆寫資料庫值。To reconcile differences between expected and actual database values before you try to resubmit your changes, you can use KeepCurrentValues to overwrite database values. 如需詳細資訊, 請參閱開放式平行存取:總覽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, an 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 overwriting database values with the current client member values.

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

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

(來自 User1)(from User1)
MariaMaria

(原始)(original)
行銷Marketing

(來自 User1)(from User1)

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

try
{
    db.SubmitChanges(ConflictMode.ContinueOnConflict);
}

catch (ChangeConflictException e)
{
    Console.WriteLine(e.Message);
    foreach (ObjectChangeConflict occ in db.ChangeConflicts)
    {
        //No database values are merged into current.
        occ.Resolve(RefreshMode.KeepCurrentValues);
    }
}
Try
    db.SubmitChanges(ConflictMode.ContinueOnConflict)

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

    For Each occ As ObjectChangeConflict In db.ChangeConflicts
        ' No database values are merged into current.
        occ.Resolve(Data.Linq.RefreshMode.KeepCurrentValues)
    Next

End Try

另請參閱See also