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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With