2011-07-02 14 views
13

私はエンティティフレームワーク4.1を使用しています。エンティティフレームワークとの並行性を処理する最良の方法は何ですか。エンティティフレームワークでそれを処理するinbuilt機能はありますか? 行バージョンを維持するためにテーブルに余分な列を追加せずに行うことはできますか?エンティティフレームワークとの並行性を処理する最良の方法

答えて

6

あなたは、このチュートリアルを見たことがあります。

26

RowVersionという名前のテーブルに列を設定し、この列をすべてのUPDATEステートメントとDELETEステートメントのwhere句に含めることをEntity Frameworkに指示できます。次に、変更されたすべてのエンティティについてこのフィールドを増やすことを確認します。私はこのようにそれをやった: http://www.asp.net/entity-framework/tutorials/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application

あなたはrowversion列なしでそれを行うことができますが、それは多くの場合、多くの状態を保存する必要があり、性能に悪影響を与えることができます。

//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はupdateとdelete文のwhere節にこれらの列を追加します。私はこれをテストしていない。 –

関連する問題