简体   繁体   English

EF CORE没有时间戳的乐观并发

[英]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 采用的解决方案依赖于在modelBuilder中调用IsConcurrencyToken

 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? 但是我真的需要为每个属性显式调用IsConcurrencyToken吗? 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: 您可以在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. 感谢David Browne的建议。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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