ADO.NET EF : Concurrency (Part 1)

In my case I may be doing a lot of save under one method and wanted to ensure if I am doing update for one single entity (table) it should prevent me to do it. I have added a table to the database with a TimeStamp column. The idea of adding the TimeStamp column is to have a column which will be changed with every modification. You could also use any other column.

 CREATE TABLE [dbo].[Emp_Concurrency](
    [Id] [int] IDENTITY(1,1) NOT NULL,
   [Name] [varchar](50) NULL,
 [TimeSt] [timestamp] NULL,
 CONSTRAINT [PK_Emp_Concurrency] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)
)

Now in the model change the property of TimeSt’s Concurrency Mode = Fixed

image

 

Now when I run the below code

 Emp_Concurrency ec = new Emp_Concurrency() { Name = "A" };
//Adding new Employee
using (TestDBEntities db = new TestDBEntities())
{                
    db.Emp_Concurrency.AddObject(ec);
    db.SaveChanges();
}

using (TestDBEntities db = new TestDBEntities())
{
    var eC = (from e1 in db.Emp_Concurrency
                where e1.Id == ec.Id
                select e1).First();
    //Console.WriteLine(eC.Name);

    //Update using Model - but not yet applied 
    eC.Name = "New Name 1";

    //Update using Query - this will try to update the db                
    db.ExecuteStoreCommand("Update Emp_Concurrency SET Name='LL' WHERE Id = {0}",ec.Id);

    try
    {                    
        db.SaveChanges();
    }
    catch (OptimisticConcurrencyException exceptionC)
    {
        Console.WriteLine("Concurrency Error!{0}", exceptionC.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception! {0}", ex.Message);
    }
}
 Now you get the below exception
 Concurrency Error!Store update, insert, or delete statement affected an unexpect
ed number of rows (0). Entities may have been modified or deleted since entities
 were loaded. Refresh ObjectStateManager entries.

Namoskar!!!