Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle concurrency with entity framework

I am using entity framework 4.1.What is the best way to handle concurrency with entity framework. Is there inbuilt functionality to handle it in entity framework? Can I do without adding extra column to the tables to keep row version?

like image 652
Jayantha Lal Sirisena Avatar asked Jul 02 '11 03:07

Jayantha Lal Sirisena


1 Answers

You can set up a column in your tables named RowVersion and tell Entity Framework that you want this column to be included in the where clauses of all UPDATE and DELETE statements. You then ensure that you increment this field for all changed entities. I've done it like this:

//make all entities that need concurrency implement this and have RowVersion field in database
public interface IConcurrencyEnabled
{
    int RowVersion { get; set; }
}
public class MyDbContext : DbContext
{
    public override int SaveChanges()
    {
        foreach(var dbEntityEntry in ChangeTracker.Entries().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified))
        {
            IConcurrencyEnabled entity = dbEntityEntry.Entity as IConcurrencyEnabled;
            if (entity != null)
            {
                entity.RowVersion = entity.RowVersion + 1;
            }
        }
        return base.SaveChanges();
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        //do all your custom model definition but have the following also:
        modelBuilder.Entity<myEntity>().Property(x => x.RowVersion).IsConcurrencyToken();
    }
}
like image 71
Marcel Gosselin Avatar answered Oct 13 '22 11:10

Marcel Gosselin