Jay*_*ena 13 concurrency ado.net entity-framework entity-framework-4.1
我正在使用实体框架4.1.使用实体框架处理并发的最佳方法是什么.是否有内置功能在实体框架中处理它?我可以不添加额外的列来保持行版本吗?
Mar*_*lin 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();
}
}
Run Code Online (Sandbox Code Playgroud)
您是否看过本教程:http: //www.asp.net/entity-framework/tutorials/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
您可以在没有rowversion列的情况下执行此操作但通常需要存储大量状态,这可能会对性能产生负面影响.
| 归档时间: |
|
| 查看次数: |
16294 次 |
| 最近记录: |