Saturday, May 16, 2015

MVC 5 scaffolding Model & Unique Key Contraint

     
    MVC 5 scaffolding allows are to build CRUD functionality on fly.but edit controller generated in such way does not handle unique key violation.So we need to add some code in our part to handle it.

Approach is quite simple first check if record violate unique key constraint in my case "Pancard" field has unique key. if such violation found then we will add validation message error as in below line

  ModelState.AddModelError("Pancard", "Unique key violation !");

My Example Model is :

    public partial class Person
    {
        public int PersonId { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Email { get; set; }
        public string Cell { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string Pancard { get; set; }
        public string Pin { get; set; }
    }

Modified Controller:

 [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="PersonId,Name,City,State,Email,Cell,Address1,Address2,Pancard,Pin")] Person person)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    //check for unique key violation
                    int cnt =(from m in db.People where m.Pancard == person.Pancard select m.Pancard).Count();
                    if (cnt ==0)
                    {
                        db.Entry(person).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }else{
                         ModelState.AddModelError("Pancard", "Unique key violation !");
                         return View(person);
                    }
                    return RedirectToAction("Index");
                }
                catch (System.Data.DataException ex)
                {
                                    
                    return RedirectToAction("Index");
                }
            }
            return View(person);
        }