TheAmazingJason
TheAmazingJason

Reputation: 63

MVC with Entity Framework Save Issue

I have a page that is used to register people for training. The current page has three drop downs on it, one to select the person to register, one to select the course, and one to select the session that the course is offered. It is being requested that the page be modified to now have four groups of the Course and Session drop downs to allow for the user to register up to four classes for a person at a time. My problem arises on how to handle the form posting now. Before if a user tried to add a person to a course they were already registered for the Entity Framework model binding would catch the error and send the error message back to the form. I'm not sure how to implement this binding now that there are four instances to evaluate and save at the same time. I'm a newbie to MVC and EF so any help/direction would greatly be appreciated.

Edit: below is a piece of the orignial controller save function:

    var AddToCourse = new Session_Registrant()
{
    RegistrantID = RegistrantID,
    SessionID = Session1,
    RegistrantOrg = regOrg,
    RegistrantTitle = title,
    RegistedDate = DateTime.Now

};
//attempt to save
try
{
    if (ModelState.IsValid)
    {
        db.AddToSession_Registrant(AddToCourse);
        db.SaveChanges();
    }
}
catch (DataException error)
{
    if (error.InnerException != null)
    {
        if (error.InnerException.Message.Contains("UNIQUE KEY constraint"))
        {
            //adding custom error message to explain the failure
            ModelState.AddModelError("", "Error! Registrant has already been added to this course session.");
        }
    }
    else
    {
        ModelState.AddModelError("Error", error.Message);
    }
}

Upvotes: 0

Views: 208

Answers (1)

Peter Smith
Peter Smith

Reputation: 5550

I wonder if the problem is with the design of the function rather than the implementation. Should the problem be defined in terms of a one-to-many relationship between the registrant entity and the course/session entity.

I am also of the view that using exceptions as part of the design is bad practice and that this is a definition problem. Should you (your code) be asking questions like:

  • Is this a registered student
  • Does this student have a course already booked in this session
  • Is this student already registered on the course in a different session

In other words define your business rules, implement them and the problem should resolve itself into a SMOC (small matter of coding).

I am sorry if this response is not more directly helpful but I feel that this is the wrong starting point. Good luck anyway.

Upvotes: 1

Related Questions