我正在使用实体框架4.1。使用实体框架处理并发的最佳方法是什么。是否有内置功能在实体框架中处理它? 我可以不在表格中添加额外的列以保留行版本吗?
答案 0 :(得分:26)
您可以在名为RowVersion的表中设置一个列,并告诉Entity Framework您希望此列包含在所有UPDATE和DELETE语句的where子句中。然后,确保为所有已更改的实体增加此字段。我这样做了:
//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();
}
}
答案 1 :(得分:6)
您可以在没有rowversion列的情况下执行此操作但通常需要存储大量状态,这可能会对性能产生负面影响。