szpic
szpic

Reputation: 4498

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:

 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:

[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. 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?

Upvotes: 0

Views: 2047

Answers (1)

Musa Hafalir
Musa Hafalir

Reputation: 1770

It would be more consistent if you would implement constraint on database.

In the Entity Framework side, you can catch exception as below:

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

Upvotes: 2

Related Questions