Domanda

I have two related tables: dbo.resources and dbo.reservation; dbo.resources has a foreign key that points to dbo.reservation with the ON DELETE SET NULL option. I also have an "after" trigger on dbo.resources, that deletes a reservation when the resource is deleted.

I have "managed" to raise an OptimisticConcurrencyException when I tried to manually delete both reservation and ressource, which would only seem normal.

I then located the problem, and eliminated it, but now i want to enforce a stronger exception handling mechanism, by catching the OptimisticConcurrencyException and refreshing the context.

My question is this: can anyone explain to me why this piece of code:

 catch (System.Data.OptimisticConcurrencyException ocException)
        {
            foreach (var objectStateEntry in ocException.StateEntries)
                _Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, objectStateEntry.Entity);
            _Context.SaveChanges();
        }

does not work,

while this one:

 catch (System.Data.OptimisticConcurrencyException ocException)
        {
            foreach (var objectStateEntry in ocException.StateEntries)
                _Context.Refresh(System.Data.Objects.RefreshMode.StoreWins, objectStateEntry.Entity);
            _Context.SaveChanges();
        }

does? How does EF treat the object context in each case (StoreWins and ClientWins)? What exactly happens "under the hood"?

È stato utile?

Soluzione

As per the reference article found here:

After the Refresh method is called, the object’s original values will always be updated with the data source value, but the current values might or might not be updated with the data source value. This depends on the RefreshMode. The StoreWins mode means that the object should be updated to match the data source values. The ClientWins value means that only the changes in the object context will be persisted, even if there have been other changes in the data source. To ensure that an object has been updated by data source-side logic, you can call the Refresh method with the StoreWins value after you call the SaveChanges method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top