I am trying to teach myself LINQ to SQL and have decided to do a small MVC.NET project to get my feet wet. The problem is that I have fallen very early on with the following error.
I am making a golf application so I have setup the database and got my dbml classes made. The database has a course
table and a hole
table. The hole
table references the courseId
by its primary key and has a foreigh key constraint on it. So all pretty standard.
I have an MVC action on my controller that allows me to edit the course information (name, and hole info, for example, par and stroke index, etc.)
When I do the save after an edit I get the following error.
"An attempt was made to remove a relationship between a Course and a Hole. However, one of the relationship's foreign keys (Hole.CourseId) cannot be set to null."
I have debugged this and can't see any problems. Is there something I need to do on the database to allow me to edit tables with foreign key constraints?
Here is the action code:
[HttpPost]
[ValidateInput(true)]
public ActionResult Edit(int id, FormCollection collection)
{
var courseViewModel = new CourseViewModel { Course = _repository.GetCourse(id) };
if (courseViewModel.Course == null)
{
return View("NotFound", string.Format("Course {0} Not Found", id));
}
try
{
UpdateModel(courseViewModel);
_repository.SubmitChanges();
return RedirectToAction("Index", "Course");
}
catch (Exception ex)
{
ModelState.AddRuleViolations(courseViewModel.Course.GetRuleViolations());
ModelState.AddModelError("", ex.Message);
return View(courseViewModel);
}
}
Where _repository looks like this:
namespace Web.Repository
{
public class MyRepository
{
private MyDataContext db = new MyDataContext();
public void SubmitChanges()
{
db.SubmitChanges();
}
public Course GetCourse(int id)
{
return db.Courses.SingleOrDefault(i => i.CourseId == id);
}
}
}