Entity Framework: Optimistic Concurrency

A short example of how can use optimistic concurrency with Entity Framework.
All you need is to create a Product table.

Very important is to set Concurrency Mode to Fixed on the model.

CREATE TABLE [dbo].[Product] (
    [ProductId] INT             IDENTITY (1, 1) NOT NULL,
    [Name]      NVARCHAR (50)   NOT NULL,
    [UnitPrice] NUMERIC (18, 2) NOT NULL,
    [Timestamp] TIMESTAMP       NOT NULL,
product table

product table

The flow is like this:
1. Create a new product
2. Retrive that product using a new instance of a context
3. Simulate an external change of that entity
4. Change the UnitPrice property within that context
5. Catch exceptions and threat them.

Uncomment line 20 to be able to refresh the entity and choose your strategy (Client wins or Store wins)

            using (var ctx = new EFLearnEntities())
                ctx.AddToProducts(new Product
                    Name = "Aaaaaa",
                    UnitPrice = 199.99M

            using (var ctx = new EFLearnEntities())
                var product = ctx.Products.FirstOrDefault();
                Console.WriteLine("{0} Unit price: {1}", product.Name,

                ctx.ExecuteStoreCommand("update product set unitprice = 229.95 where productid = @p0",

                //ctx.Refresh(System.Data.Objects.RefreshMode.ClientWins, product);
                product.UnitPrice = 200.01M;

                catch (OptimisticConcurrencyException oce)
                    Console.WriteLine("Optimistic Concurrency {0}", oce.Message);
                catch (Exception ex)
                    Console.WriteLine("Exception {0}", ex.Message);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s