Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Entity Framework optimistic concurrency (database wins) pattern

See Resolving optimistic concurrency exceptions with Reload (database wins) :

using (var context = new BloggingContext())
{
    var blog = context.Blogs.Find(1);
    blog.Name = "The New ADO.NET Blog";
    bool saveFailed;
    do
    {
        saveFailed = false;

        try
        {
            context.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            saveFailed = true;

            // Update the values of the entity that failed to save from the store
            ex.Entries.Single().Reload();
        }

    } while (saveFailed);
}

Why the method SaveChanges() is called after Reload()? This call will never change the data in the database.

like image 410
DeeRain Avatar asked Feb 19 '13 18:02

DeeRain


People also ask

What is optimistic concurrency in Entity Framework?

EF Core implements optimistic concurrency control, meaning that it will let multiple processes or users make changes independently without the overhead of synchronization or locking. In the ideal situation, these changes will not interfere with each other and therefore will be able to succeed.

How does Entity Framework maintain concurrency?

If you do want to implement this approach to concurrency, you have to mark all non-primary-key properties in the entity you want to track concurrency for by adding the ConcurrencyCheck attribute to them. That change enables the Entity Framework to include all columns in the SQL WHERE clause of UPDATE statements.

How do you handle optimistic concurrency exceptions?

To resolve optimistic concurrency conflicts, you can take advantage of the Reload method to update the current values in your entity residing in the memory with the recent values in the database. Once reloaded with the updated data, you can attempt to persist your entity again in the database.

What are the different relationship patterns in Entity Framework?

Entity framework supports three types of relationships, same as database: 1) One-to-One 2) One-to-Many, and 3) Many-to-Many.


1 Answers

I agree it's not too clear. The intention of this piece of code is in the sentence

The entity is then typically given back to the user in some form and they must try to make their changes again and re-save.

So it would have been better if they had added a comment:

...
// User evaluates current values and may make new changes.
try
{
    context.SaveChanges();
}
...
like image 121
Gert Arnold Avatar answered Nov 15 '22 08:11

Gert Arnold