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嘗試添加重複時引發?
是的,我對數據庫約束,這就是爲什麼我能趕上DbUpdateException。順便說一句,你忘了從xx aspx – szpic
謝謝@szpic,我已經修復它。 –