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,
    PRIMARY KEY CLUSTERED ([ProductId] ASC)
);
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
                });
                ctx.SaveChanges();
            }

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

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

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

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

            Console.ReadLine();
Advertisements