0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I have constraint on database that's why I can catch DbUpdateException. Btw you forgot "x" from aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.