2011-07-02 16 views

Odpowiedz

26

Możesz ustawić kolumnę w tabelach o nazwie RowVersion i powiedzieć Entity Framework, że chcesz, aby ta kolumna była zawarta w klauzulach where wszystkich instrukcji UPDATE i DELETE. Następnie upewnij się, że zwiększasz to pole dla wszystkich zmienionych jednostek. Zrobiłem to tak:

//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

Przeczytałem to pytanie. ma inny pomysł, dziękuję http://stackoverflow.com/questions/3412690/entity-framework-objectcontext-concurrency –

+1

Nie mogę tego zrobić bez kolumny wersji wiersza? –

+1

Myślę, że możesz ustawić więcej niż jedną właściwość z 'IsConcurrencyToken()', a EF doda te kolumny w klauzuli where instrukcji aktualizacji i usuwania. Nie testowałem tego jednak. –

Powiązane problemy