Best way to handle concurrency with entity framework

别来无恙 提交于 2019-12-18 10:29:18

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/6554860/best-way-to-handle-concurrency-with-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!