Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable concurrency checking using EF 5.0 Code First?

I would like to do a check-then-update in an atomic operation. I am using dbcontext to manage the transaction. I was expecting to get an exception if the record has been modified by another thread but no exception is thrown. Any help would be appreciated. Here's my output:

Thread-4: Reading...
Thread-5: Reading...
Thread-5: Updating destination 1
Thread-4: Updating destination 1
Thread-4: SaveChanges
Thread-5: SaveChanges

Here's my code snippet:

public static void Main(string[] args)
{
    PopulateData();
    (new Thread(UpdateDestination1)).Start();
    (new Thread(UpdateDestination1)).Start();
}

public static void UpdateDestination1()
{
    using (var context1 = new BreakAwayContext())
    {
        Console.WriteLine("Thread-{0}: Reading...", Thread.CurrentThread.ManagedThreadId);
        var d = context1.Destinations.FirstOrDefault();
        Console.WriteLine("Thread-{0}: Updating destination {1}", Thread.CurrentThread.ManagedThreadId, d.DestinationId);
        d.Name = "Thread-" + Thread.CurrentThread.ManagedThreadId;
        try
        {
            context1.SaveChanges();
            Console.WriteLine("Thread-{0}: SaveChanges", Thread.CurrentThread.ManagedThreadId);
        }
        catch (OptimisticConcurrencyException)
        {
            Console.WriteLine("OptimisticConcurrencyException!!!");
            throw;
        }
    }
}
like image 526
user1342718 Avatar asked Oct 25 '12 03:10

user1342718


People also ask

How can we enable concurrency mode in Entity Framework?

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.

Which concurrency approach is not supported in EF core?

Entity Framework Core provides no support for pessimistic concurrency control.

What is concurrency token in entity framework?

A timestamp/rowversion is a property for which a new value is automatically generated by the database every time a row is inserted or updated. The property is also treated as a concurrency token, ensuring that you get an exception if a row you are updating has changed since you queried it.


1 Answers

You can use ConcurrencyCheck annotation on a property ( http://msdn.microsoft.com/en-us/data/gg193958.aspx ) or IsConcurrencyToken() or .IsRowversion when configuring a property with fluent API ( http://msdn.microsoft.com/en-us/data/jj591617#1.12). Typically you would have a rowversion column in the database.

like image 126
Pawel Avatar answered Oct 18 '22 01:10

Pawel