如何使用aspboilerplate和Entity Framework Core处理ASP.NET Framework 4.6.1中的并发

时间:2019-01-09 12:08:58

标签: asp.net entity-framework-core

我正在尝试使用添加到实体中的RowVersion属性在应用程序中设置开放式并发。

我找不到

  

DbUpdateConcurrencyException

出现在测试过程中。

我所做的测试是在实体上运行更新SQL命令,而在前端将相同的实体加载到内存中。

有人对我要去哪里有什么想法吗?

测试SQL脚本:

UPDATE [dbo].[MyEntity]
SET [Name] = 'fdgopiifdgdf'
WHERE [Id] = '64E7C7AE-DF4E-4F24-B321-384772CD1186'

实体:

[Table("MyEntity")]
public class MyEntity : FullAuditedEntity<Guid>, IConcurrencyCheck
{
    [Required]
    public virtual string Name { get; set; }

    public virtual int Order { get; set; }
    public virtual bool Active { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
}

Dto:

public class CreateOrEditMyEntityDto : EntityDto<Guid?>
{
    [Required]
    public string Name { get; set; }

    public int Order { get; set; }
    public bool Active { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
}

实体的CustomDtoMapper:

configuration.CreateMap<MyEntity, MyEntityDto>();

DbContext OnModelCreating方法:

modelBuilder.Entity<MyEntity>()
    .Property(a => a.RowVersion)
    .IsRowVersion()
    .IsConcurrencyToken()
    .ValueGeneratedOnAddOrUpdate();

编辑实体方法:

public async Task Update(CreateOrEditMyEntityDto input)
{
    //Handle multi processing concurrency issues.
    try
    {
        var MyEntity = await _MyEntityRepository.FirstOrDefaultAsync((Guid)input.Id);
        ObjectMapper.Map(input, MyEntity);
    }
    catch (DbUpdateConcurrencyException)
    {
        throw new UserFriendlyException("Please reload to edit this record.");
    }
}

我在这里工作的是我在DbContext文件中使用RowVersion时间戳所做的。

protected override void ApplyAbpConceptsForModifiedEntity(EntityEntry entry, long? userId, EntityChangeReport changeReport)
{
    if (entry.OriginalValues.GetType().GetProperty("RowVersion") != null)
    {
        entry.OriginalValues["RowVersion"] = entry.CurrentValues["RowVersion"];
    }

    base.ApplyAbpConceptsForModifiedEntity(entry, userId, changeReport);
}

0 个答案:

没有答案