Ghini Antonio
Ghini Antonio

Reputation: 3132

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?

Upvotes: 2

Views: 313

Answers (2)

Ghini Antonio
Ghini Antonio

Reputation: 3132

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

Upvotes: 0

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89361

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);
}

Upvotes: 4

Related Questions