具有唯一约束的实体框架更新查询

时间:2014-01-29 08:54:38

标签: c# entity-framework

我想问你,最好的办法是什么。

我有一个独特字段的表。

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是否是唯一的:

 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框架方法:

[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);
    }

现在我无法更新任何记录,因为isUnique始终返回serialNo已经存在。什么是真的。

现在我的问题。它更好的修改是unique方法,以某种方式或 删除isUnique方法并为尝试添加重复时抛出的dbUpdateException添加catch?

1 个答案:

答案 0 :(得分:2)

如果要对数据库实施约束,那将更加一致。

在Entity Framework方面,您可以捕获异常,如下所示:

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 Numbers:http://msdn.microsoft.com/en-us/library/cc645603.aspx

相关问题