Wednesday, 17 April 2013

Checking for duplicate when creating new object from MVC

I am creating new objects using the wonderful MVC4 scaffolding from my models and one issue I noticed is where I don't have a primary key or unique constraint on a table column but where I still want that column to be unique. Of course, the logic could be more complex, such as you are only allowed to duplicate the "name" if the previous object of the same name has expired. This might be kind of easy to code but here is an example anyway. In my controller method for Create(model), you can add additional logic to check before the item is added to the entity list and saved. There are loads of linq expressions at your disposal but .Any<> is probably the one most useful for this:

        public ActionResult Create(DiscountCodeModel discountcodemodel)
            if (ModelState.IsValid && !db.DiscountCodeModels.Any( m => m.CodeHash == discountcodemodel.CodeHash))
                return RedirectToAction("Index");
            if (db.DiscountCodeModels.Any(m => m.CodeHash == discountcodemodel.CodeHash))
                ViewBag.ErrorMessage = "Code already exists";

            return View(discountcodemodel);

This (not very tidy modification) will not save the entity if the hash of the entered code matches the hash of any existing item and if so, it sets a viewbag message and returns the current view again. The same code is used if there are validation errors therefore I guard the error message with another of the same if statements. I'm sure you could all re-factor this to make it tidier!

No comments: