Entity framework 5.0 handle optimistic concurrency exception?

后端 未结 2 1262
我在风中等你
我在风中等你 2020-12-13 02:52

When handling several potential exceptions during a context.SaveChanges() one of the exceptions is OptimisticConcurrency. Microsoft\'s documentatio

2条回答
  •  不思量自难忘°
    2020-12-13 03:14

    The way how to solve concurrency exception in DbContext API reloads original entity:

    catch (DbUpdateConcurrencyException ex)
    {
        // Get failed entry
        var entry = ex.Entries.Single(...);
        // Overwrite original values with values from database but don't
        // touch current values where changes are held
        entry.OriginalValues.SetValues(entry.GetDatabaseValues());
    }
    

    You should also be able to use the mentioned code but you must get ObjectContext instance from your DbContext instance (it is just a wrapper around ObjectContext).

    catch (DbUpdateConcurrencyException ex)
    {
        var objContext = ((IObjectContextAdapter)context).ObjectContext;
        // Get failed entry
        var entry = ex.Entries.Single(...);
        // Now call refresh on ObjectContext
        objContext.Refresh(RefreshMode.ClientWins, entry.Entity);        
    }
    

    You may even try:

    objContext.Refresh(RefreshMode.ClientWins, ex.Entries.Select(e => e.Entity));
    

提交回复
热议问题