处理乐观并发MVC编辑表

时间:2018-11-05 18:46:05

标签: c# asp.net-mvc entity-framework optimistic-concurrency

我的下面的编辑表单有问题,它从不捕获 DbUpdateConcurrencyException 。我究竟做错了什么?

课程

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

控制器

[AcceptVerbs("POST", "PUT")]
public ActionResult EditData(System.Web.Mvc.FormCollection formData) 
{

int year = Convert.ToInt32(formData["year"]);
int itemID = Convert.ToInt32(formData["itemID"]);
byte[] rowVersionID = Encoding.UTF8.GetBytes(formData["RowVersion"]);
string row = Convert.ToBase64String(rowVersionID);    

if (ModelState.IsValid) {
string[] itemIDArray = formData.GetValues("item.itemID");

using(BusinessLogicLayer BLL = new BusinessLogicLayer()) {

   for (int i = 0; i < itemIDArray.Count(); i++) {
    try   
    {        
     BLL.UpdateItem(Convert.ToInt32(itemIDArray[i]));

     BLL.SaveChanges();

    } 

 catch (DbUpdateConcurrencyException ex) //it never catches the exception

    {

     // Get the current entity values and the values in the database 
     // as instances of the entity type 
     var entry = ex.Entries.Single();
     var databaseValues = entry.GetDatabaseValues();

     ModelState.AddModelError(string.Empty, "The record you attempted to 
     edit has been modified by another user. Please try again!");      
    }
   }
  }
 }

 return View();
}
}
}

我还将RowVersion列“ Concurrency Mode”设置为固定

enter image description here

编辑

我还将catch块异常更改为通用异常,现在我收到以下错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

这可能是另一种异常类型。将catch块更改为通用Exception:

catch (Exception e){
    // your catch code
}

然后查看其引发的错误类型并相应地调整代码。