2011-07-02 52 views

回答

26

你可以設置你的命名RowVersion表列,並告訴您要包​​含在所有UPDATE的WHERE子句此列和DELETE語句實體框架。然後確保您爲所有更改的實體增加此字段。我已經做了這樣的:

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

我看過這個問題。它有一個不同的想法謝謝http://stackoverflow.com/questions/3412690/entity-framework-objectcontext-concurrency –

+1

我不能沒有行版本列嗎? –

+1

我想你可以用'IsConcurrencyToken()'設置多個屬性,EF會在更新和刪除語句的where子句中添加這些列。我還沒有測試過。 –