我有以下实体,
public class PatientRegistry : BaseEntity {
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Patient File Number")]
public long PatientFileId { get; set; }
public virtual ICollection<PartnerRegistry> Partners { get; set; }
public string UserId { get; set; }
public string AliasName { get; set; }
public DateTime? DateNow { get; set; }
public virtual ApplicationUser User { get; set; }
}
BaseEntity是
public class BaseEntity : ISoftDelete {
public bool IsDeleted { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
该实体具有RowVersion
属性,我使用流畅的API将其配置为RowVersion。我使用存储库模式,这就是在上下文中加载实体的方式,
public async Task<PatientRegistry> GetPatient(long Id, bool isPartners = true, bool isUser = true) {
if (isPartners && !isUser)
return await context.PatientsRegistry
.IgnoreQueryFilters()
.Include(pt => pt.Partners)
.Include(pt => pt.User)
.Include(pt => pt.User.Gender)
.Include(pt => pt.User.Nationality)
.Include(pt => pt.User.Occupation)
.Include(pt => pt.User.Ethnicity)
.Include(pt => pt.User.MaritalStatus)
.Include(pt => pt.User.Country)
.Include(pt => pt.User.State)
.Include(pt => pt.User.City)
.Include(pt => pt.User.Database)
.Include(pt => pt.User.UserAvatar)
.SingleOrDefaultAsync(pt => pt.PatientFileId == Id);
}
在我的控制器中,我进行了如下更新,
[HttpPut("{FileId}")]
public async Task<IActionResult> UpdatePatient([FromRoute] PatientFileIdResource fileIdModel, [FromBody] SavePatientsRegistryResource model)
{
ApiSuccessResponder<PatientRegistryResource> response = new ApiSuccessResponder<PatientRegistryResource>();
if (!ModelState.IsValid)
return BadRequest(ModelState);
Task<PatientRegistry> getPatientTask = repository.GetPatient(fileIdModel.FileId.Value);
Task<RequestHeaderResource> getHeaderRequestTask = headerRequestService.GetUserHeaderData();
await Task.WhenAll(getPatientTask, getHeaderRequestTask);
PatientRegistry patient = await getPatientTask.ConfigureAwait(false);
RequestHeaderResource header = await getHeaderRequestTask.ConfigureAwait(false);
if (patient == null)
{
ModelState.AddModelError(string.Empty, "The patient does not exist in the database");
return BadRequest(ModelState);
}
patient.DateNow = DateTime.Now;
patient.AliasName = model.AliasName;
await unitOfWork.CompleteAsync(header);
return StatusCode(200, response);
}
现在,如果我有两个不同的用户访问同一个记录,并且其中一个更改AliasName
并保存了第二个访问该记录的用户,那么在没有并发异常的情况下,仍然可以保存新的更改。为什么这里的并发更新没有引发更新异常?
这是Fluent API配置,
builder.Entity<PatientRegistry>()
.Property(a => a.RowVersion).IsRowVersion()
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate();
我有更新日志here
更新
供以后参考,
基于文档here,我们可以通过在调用save之前操作一个值来测试并发冲突。
即
context.Database.ExecuteSqlCommand("UPDATE dbo.PatientsRegistry SET AliasName = 'Jane' WHERE PatientFileId = 2222");
await context.SaveChangesAsync();
这将引发异常。
答案 0 :(得分:4)
如果第二个用户的读取是在之后,那么第二个用户的RowVersion
将反映当时的值(即,之后第一次更新)。因此-没有并发问题。
只有当他们都读(并因此得到相同的RowVersion
)并且然后都尝试写时,您才会遇到问题。