Validation in MVC Entity Framework to avoid duplicate records

asp.net-mvc entity-framework validation

Question

Hello, I may have a really basic question since I'm new to MVC and EF, but what is the best approach to stop a user from attempting to input duplicate records?

I have a straightforward look-up table with only one column—the main key. In order for administrators to add more entries to the lookup list, I'm creating a maintenance screen. My controller seems to be:

public ActionResult Index(string NewRow)
    {
        try
        {
            CaseType t = new CaseType { ID = NewRow };
            if (ModelState.IsValid)
            {
                UOW.CaseTypes.Add(t);
                UOW.Save();
            }
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
        }
        return View(UOW.CaseTypes.All());
    }

It prevents the yellow screen of death and duplicate data, however the statement that appears is: "The entries were being updated when an issue occurred. Details are provided in the inner exception." it is detrimental to the users.

Just wondering whether there's a more effective technique to spot the mistake.

1
2
7/5/2013 10:07:28 AM

Accepted Answer

ZZZ_tmp
4
5/23/2017 12:08:26 PM

Popular Answer

You may follow these steps to get the inner exception:

catch (Exception ex)
        {
           while(ex.InnerException!=null){
                 ex=ex.InnerException;
           }
            ModelState.AddModelError("", ex.Message);
        }

I'm not quite sure about the syntax:



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow