简体   繁体   中英

EF CORE Optimistic concurrency without timestamp

I'm working with a bounch of entities each of them having several properties. Each property is involved in optimistic concurrency check on saving. I prefer avoid using of timestamp as I should add the field on each tables, Im working with a legacy database and I don't want to make any changes on it. The solution adopted rely on calling IsConcurrencyToken in the modelBuilder

 protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<MyEntity1>(entity =>
                {
                    entity.Property(e => e.Property1).IsConcurrencyToken;
                    entity.Property(e => e.Property2).IsConcurrencyToken;
                    entity.Property(e => e.Property3).IsConcurrencyToken;


                    entity.Property(e => e.PropertyN).IsConcurrencyToken;
                });         
             }

but do I really need to explicitly call IsConcurrencyToken for every properties? Is there any chance to configure my entities to automatically include every properties in the concurrency check?

Is there any chance to configure my entities to automatically include every properties in the concurrency check?

Yes. You can iterate over all your entities and properties in OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var prop in entity.GetProperties())
        {
            prop.IsConcurrencyToken = true;
        }
    }

    base.OnModelCreating(modelBuilder);
}

Thanks to David Browne for the suggestion.

As I want to be able to enable concurrency entity by entity I wrapped the code in extension method

  public static EntityTypeBuilder<TEntity> EnableConcurrency<TEntity>(this EntityTypeBuilder<TEntity> entityTypeBuilder) where TEntity : class
        {
            var entity = entityTypeBuilder.Metadata.Model.FindEntityType(typeof(TEntity));
            foreach (var prop in entity.GetProperties())
            {
                prop.IsConcurrencyToken = true;
            }
            return entityTypeBuilder;
        }

and Im going to use it like that

modelBuilder.Entity<MyEntity>(entity =>
            {
                entity.EnableConcurrency();
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM