1. 程式人生 > >使用EFCore處理並發沖突

使用EFCore處理並發沖突

字段 nbsp value n) TE 新的 base context min

一、首先在需要進行並發處理的字段上加上[Timestamp]標記:

public class Department
{
     public int Id { get; set;}
     public int? InstructorId{ get; set; }
     public ICollection<Course> Courses {get; set; }

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

二、然後更新數據庫

add-migration updateTimestampForDeparment

update-database

三、重新建基架項目

刪除Create和Edit頁面內關於RowVersion項目的輸入項

四、打開編輯Edit的控制器,修改如下:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, byte[]rowVersion)
{
       if(id==null)
       {
              return NoFound();
       }
       //先查一下數據是否存在
       var department= await
_context.Departments.Include(a=>a.Administrator) .SingleOrDefaultAsync(a=>a.Id==id); if(department==null) { var deletedDepartment=new Department(); await TryUpdateModeAsync(deletedDepartment); ModelState.AddModelError(
string.Empty,"無法進行數據的修改,該部門信息已經被其他人刪除!); ViewData["InstructorId"]=new SelectList(_context.Instructors, "Id","RealName",deletedDepartment); return View(deletedDepartment); } //將RowVersion標誌原來的值變更為新的值 _context.Entry(department).Property("RowVersion").OriginalValue = rowVersion; if(await TryUpdateModelAsync<Department>(department, a=>a.Name, a=>a.StartDate, a=>a.Budge(a=>a.InstructorId)) { try { } catch() { } } }

使用EFCore處理並發沖突