title: In Entity Framework, how to delete record with foreign key constraint?
body: <p>I have a method to delete a "project" record in the database, and all the "option items" associated with it.</p>
  
  <pre><code>public bool DeleteProjectById(int id)
  {
      using (DbContext db = new DbContext(ConfigHelper.Instance().ConnectionString))
      {
          try
          {
              foreach (var entity in db.ProjectOptionItems.Where(o =&gt; o.ProjectId == id))
                  db.ProjectOptionItems.DeleteObject(entity);
  
              db.SaveChanges();
  
              var project = db.Projects.SingleOrDefault(o =&gt; o.Id == id);
              db.Projects.DeleteObject(project);
  
              db.SaveChanges();
              return true;
          }
          catch (Exception e)
          {
              ErrorLoggingService.Log(this, e);
              return false;
          }
      }
  }
  </code></pre>
  
  <p>This works fine. But if I comment out the first call to <strong>db.SaveChanges</strong>, which is by the way how I was hoping the code will be, this will result to an SQL exception (<em>The DELETE statement conflicted with the REFERENCE constraint</em>).</p>
  
  <p>Having two calls to SaveChanges() works but surely this is not the way to do it. Please help. Thanks!</p>