开发者

Resolve Concurrency Conflicts by Overwriting Database Values of deleted objects(LINQ to SQL)

开发者 https://www.devze.com 2023-02-22 11:22 出处:网络
I want to implement a somewhat generic conflict handler. In the process I encountered the case where a conflict occurs due to an attempt to change a deleted object.

I want to implement a somewhat generic conflict handler.

In the process I encountered the case where a conflict occurs due to an attempt to change a deleted object.

In general I want the user to choose whether to persist his changes no matter what, or to cancel them. That is why my handler asks feedback from the user.

So I want to be able to, if/ when I encounter a deleted entity, to re-insert this entity if the user chooses to do so.

I have tried using the Metatable data of the ObjectChangeConflict to Insert the object in the Datatable but, although the entity is not in the table anymore (does not appear in the Data Context), I get an exception that I cannot add an already existing entity.

My code is the following:

GmngrDatabaseContextDataContext formDbContext;
RefreshMode UserSelectedConfilctResolutionSceme; 
开发者_高级运维

// resolve all conflicts according to the desires of the user
foreach (ObjectChangeConflict occ in formDbContext.ChangeConflicts)
{
    occ.Resolve(UserSelectedConfilctResolutionSceme, true);

    // Conflicted due to deleted object?
    if (occ.IsDeleted && UserSelectedConfilctResolutionSceme == RefreshMode.KeepCurrentValues)
    {
        try
        {
            MetaTable metatable = formDbContext.Mapping.GetTable( occ.Object.GetType() );
            formDbContext.GetTable( metatable.RowType.Type ).InsertOnSubmit( occ.Object );
        }
        catch (Exception ex)
        {
            string err = ex.Message;
        }
    }
}

formDbContext.SubmitChanges(ConflictMode.FailOnFirstConflict);

How else can I perform this task? Thank you in advance.


First, You are getting the exception becuase indeed the entity is already in the data context (otherwise the conflict was not raised from the begining).

I can think of 2 options of doing so:

  1. If the you don't need the primary key to be the same as the key of the deleted entity (if the key is just an identity for example) you can create a new entity, copy the values of the conflicting entity to this new entity and insert it instead of insert the entity that failed.

  2. If the primary key is important and you insist to insert the entity you have in your hands, I suggest to use different datacontext that does not "knows" this entity and insert it using this context.

Hope it helps,

Koby

0

精彩评论

暂无评论...
验证码 换一张
取 消