a doubt about EF synatx RRS feed

  • Question

  • I followed the following document:

    and when I run the following code:

    [HttpPost] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { try { Student student = db.Students.Find(id); db.Students.Remove(student); db.SaveChanges(); } catch (DataException/* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. return RedirectToAction("Delete", new { id = id, saveChangesError = true }); } return RedirectToAction("Index"); }

    the student which id is specified, I assume id=2 ( student id). so when I run above code, the id=2( student id) of the student table has bee deleted, this is excepted. But the information about id=2 (student id) from other two tables course and enrollment also be deleted too. So I just want to know why?
    • Edited by GoyourGod Friday, March 31, 2017 6:03 AM
    Friday, March 31, 2017 5:59 AM


  • I think your tables are like Course -> Enrollment <- Student where course can have multiple student enrollments and student can have enrollments to multiple courses. So the relation between course and student is many-to-many. Now if student is deleted, then delete cascades to Enrollment table so that students every enrollment is also deleted. That is expected because there is no point to have enrollments to deleted student and reference integrity is maintained. But if also Course got deleted then you should check your database and verify that delete to Enrollment table do not cascade to Course table.
    • Marked as answer by GoyourGod Tuesday, June 6, 2017 12:33 AM
    Friday, April 7, 2017 12:04 PM