简体   繁体   English

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

[英]Entity Framework update query with Unique constraint

I wan to ask you what is best way to get this work. 我想问你最好的办法是什么。

I have table with one unique field. 我有一个独特的领域表。

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

and I have simple method for checking if SerialNo is unique: 我有简单的方法来检查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;
    }

And enity framework method to edit records in table: 和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);
    }

Now I can't update any record because isUnique always returns that serialNo already exists. 现在我无法更新任何记录,因为isUnique总是返回serialNo已经存在。 What is true . 什么是真的

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? 它更好地修改isUnique方法,或者删除isUnique方法并为尝试添加重复时抛出的dbUpdateException添加catch?

It would be more consistent if you would implement constraint on database. 如果要在数据库上实现约束,那将更加一致。

In the Entity Framework side, you can catch exception as below: 在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;
        }
    }
}

You can find SqlException Numbers in the document: http://msdn.microsoft.com/en-us/library/cc645603.aspx 您可以在文档中找到SqlException Numbers: http//msdn.microsoft.com/en-us/library/cc645603.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM