I have the following Model
public class CourseModel
{
[Key]
public int courseID { get; set; }
...
public virtual ICollection<CourseMeetModel> meets { get; set; }
}
When I try to edit one of the entries and if the input is valid it works fine. However if the if its not valid it alerts the user of the mistakes. Once the user fixes the mistakes and tries to save i get the following exception.
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
I have noticed this happens if the input fails the validation steps in my controller.
My Controller
public ActionResult EditCourseConfirmed(CourseModel course)
{
CoursesDBContext db = new CoursesDBContext();
bool valid = validateCouse(course); //If this fails and the course model is returned back to the view I get that error
if (valid)
{
try
{
db.Entry(course).State = EntityState.Modified;
db.SaveChanges();
Session[d.s_Clear] = false;
return RedirectToAction("Index");
}
catch (Exception e)
{
ModelState.AddModelError(string.Empty, "Unable to save the course, please try again." + e.Message);
return View(course);
}
}
return View(course);
}