2014-01-29 37 views
0

我想問你什麼是最好的方式來獲得這項工作。使用唯一約束條件的實體框架更新查詢

我有一個獨特的領域的表。

public partial class DeviceInstance 
{ 
    public int Id { get; set; } 
    [Required] 
    public int DeviceId { get; set; } 
    [Required] 
    [MaxLength(50)] 
    public string SerialNo { get; set; } <--- This field is unique 
    [Required] 
    public System.DateTime CreationDate { get; set; } 
} 

,我有檢查簡單的方法,如果是的SerialNo獨特:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Edit([Bind(Include="Id,DeviceId,SerialNo,CreationDate")] DeviceInstance deviceinstance) 
    { 
     if (ModelState.IsValid) 
     { 
      if(IsUnique(deviceinstance.SerialNo)) 
      { 
       db.Entry(deviceinstance).State = EntityState.Modified; 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      else 
      { 
       ModelState.AddModelError("", "Numer seryjny nie jest unikalny"); 
      } 
     } 
     ViewBag.DeviceId = new SelectList(db.Devices, "Id", "Name", deviceinstance.DeviceId); 
     ViewBag.Id = new SelectList(db.DeviceUsages, "DeviceInstanceId", "DeviceInstanceId", deviceinstance.Id); 
     return View(deviceinstance); 
    } 

現在我不能更新任何:

public bool IsUnique(String value) 
    { 
     if (!String.IsNullOrEmpty(value)) 
     { 
      var No = value.ToString(); 
      var a = db.DeviceInstances.Where(model => model.SerialNo == No).FirstOrDefault(); 
      if (a == null) 
      { 
       return true; 
      } 
     } 
     return false; 
    } 

而且enity框架方法表編輯記錄因爲isUnique始終返回serialNo已經存在的記錄。什麼是真實的。

現在我的問題。它更好地修改isUnique方法或 刪除isUnique方法,並添加捕獲的dbUpdateException嘗試添加重複時引發?

回答

2

如果您要對數據庫實施約束,則會更加一致。

在實體框架的一面,你可以捕捉異常如下:

try 
{ 
    using (var context = new YourEntityContext()) 
    { 
     context.DeviceInstance.Add(new DeviceInstance() { /*Properties*/ }); 
     context.SaveChanges(); 
    } 
} 
catch (DbUpdateException ex) 
{ 
    var sqlexception = ex.InnerException.InnerException as SqlException; 
    if (sqlexception != null) 
    { 
     if (sqlexception.Errors.OfType<SqlError>().Any(se => se.Number == 2601)) 
     { 
      // Duplicate Key Exception 
     } 
     else 
     { 
      // Sth Else 
      throw; 
     } 
    } 
} 

您可以在文檔中找到SQLEXCEPTION編號:http://msdn.microsoft.com/en-us/library/cc645603.aspx

+0

是的,我對數據庫約束,這就是爲什麼我能趕上DbUpdateException。順便說一句,你忘了從xx aspx – szpic

+0

謝謝@szpic,我已經修復它。 –