title: Entity Framework update query with Unique constraint
body: <p>I wan to ask you what is best way to get this work.</p>
  
  <p>I have table with one unique field.</p>
  
  <pre><code>public partial class DeviceInstance
  {
      public int Id { get; set; }
      [Required]
      public int DeviceId { get; set; }
      [Required]
      [MaxLength(50)]
      public string SerialNo { get; set; } &lt;--- This field is unique
      [Required]
      public System.DateTime CreationDate { get; set; }
  }
  </code></pre>
  
  <p>and I have simple method for checking if SerialNo is unique:</p>
  
  <pre><code> public bool IsUnique(String value)
      {
          if (!String.IsNullOrEmpty(value))
          {
              var No = value.ToString();
              var a = db.DeviceInstances.Where(model =&gt; model.SerialNo == No).FirstOrDefault();
              if (a == null)
              {
                  return true;
              }
          }
          return false;
      }
  </code></pre>
  
  <p>And enity framework method to edit records in table:</p>
  
  <pre><code>[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);
      }
  </code></pre>
  
  <p>Now I can't update any record because isUnique always returns that serialNo already exists. What is true .</p>
  
  <p>And now my question. Its better modify isUnique method to someway or
  delete isUnique method and add catch for the dbUpdateException which is thrown when trying to add duplicate?</p>