John John
John John

Reputation: 1

Can not Catch DbUpdateException raised in my repositiry at my controller method

i have the following register action method :-

[AcceptVerbs(HttpVerbs.Post)]
        public PartialViewResult Register(string id, int classid) {

           try
{
 User user = r.FindUser(id);
            Users_Classes uc = new Users_Classes();
            uc.AddedDate = DateTime.Now;
            uc.ClassID = classid;
            user.Users_Classes.Add(uc);
            repository.Save();
            ViewBag.classid = classid;
            return PartialView("_usersearch2", uc);
}
    catch (System.Data.UpdateException ex)
           { 
    return PartialView("_error");}  }

which calls the following Save method inside the repository class:-

public void Save() {
            entities1.SaveChanges();
        }

I am facing the following two problems wiht the above code:-

  1. incase two system users register the same User at the same class then the following exception will be raised DbUpdateException on the repository.Save(); and the catch (System.Data.UpdateException ex) will not handle it . so how i can force the exception to be passed to my action method?

  2. how i can return an alert box (which indicates that the user might have been already added to this class) if the exception occur, instead of returning PartialView("_error");} ?.

BR

Upvotes: 1

Views: 877

Answers (1)

rasmusvhansen
rasmusvhansen

Reputation: 1522

1) As far as I can see, DbUpdateException is not a sub-class of UpdateException, so if you want to catch DbUpdateException you should probably catch that specifically. Alternatively you can catch a DataException which is the base class for both UpdateException and DbUpdateException

Upvotes: 1

Related Questions