Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't save changes to child tables using LINQ to SQL that have foreign key constraints
    primarykey
    data
    text
    <p>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.</p> <p>I am making a golf application so I have setup the database and got my dbml classes made. The database has a <code>course</code> table and a <code>hole</code> table. The <code>hole</code> table references the <code>courseId</code> by its primary key and has a foreigh key constraint on it. So all pretty standard.</p> <p>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.)</p> <p>When I do the save after an edit I get the following error.</p> <p>"<strong><em>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</em></strong>."</p> <p>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?</p> <p>Here is the action code:</p> <pre><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); } } </code></pre> <p>Where _repository looks like this:</p> <pre><code> 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 =&gt; i.CourseId == id); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload