Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21376

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?

Upvotes: 13

Views: 16847

Answers (2)

tdykstra
tdykstra

Reputation: 6060

Have you seen this tutorial: http://www.asp.net/entity-framework/tutorials/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application

You can do it without a rowversion column but that often requires storing a lot of state, which can adversely affect performance.

Upvotes: 6

Marcel Gosselin
Marcel Gosselin

Reputation: 4716

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();
    }
}

Upvotes: 26

Related Questions