title: Adding and removing data from the db using Entity Framework
body: <p>I have several tables in the DB and I want to remove all the data and repopulate the tables and only then perform a save changes (because in case the save fails I want to return to the old data).</p>
  
  <p>when I remove the data from the DB and then try to add the data into the DB it fails and says "Adding a relationship with an entity which is in the Deleted state is not allowed.", but when I remove the data then <strong>save</strong> and then add the new data and saves again, everything works fine..</p>
  
  <p>here is my code if it helps understanding the problem </p>
  
  <pre><code>// create the new data
  SomeDataHolder data = ... ; 
  // save some data to re-enter back after changes
  List&lt;User&gt; usersSave = ctx.Users.ToList(); 
  List&lt;UserPreferences&gt; userPrefsSave = ctx.UserPreferences.ToList(); 
  
  //clear DB
  ctx.UserCourses.RemoveRange(ctx.UserCourses);
  ctx.Users.RemoveRange(ctx.Users);
  ctx.Specializtions.RemoveRange(ctx.Specializtions);
  ctx.Course_Predecessor.RemoveRange(ctx.Course_Predecessor);
  ctx.Courses.RemoveRange(ctx.Courses);
  ctx.Departments.RemoveRange(ctx.Departments);
  ctx.GroupsDetails.RemoveRange(ctx.GroupsDetails);
  ctx.LinkTable.RemoveRange(ctx.LinkTable);
  </code></pre>
  
  <p><strong>this next line makes everything works, without this line the code will fail on next save</strong></p>
  
  <pre><code>// ctx.SaveChanges(); 
  
  updateDepartmentsCoursesSpecialization(ctx, data.Specializations);
  updateCoursePredecessorsAndParallel(ctx, data.Predecessors);
  updateGroupDetails(ctx, data.GroupDetails);
  updateLectureToPractice(ctx, data.LinkLectureWithPractice);
  ctx.Users.AddRange(usersSave);
  ctx.UserPreferences.AddRange(userPrefsSave);
  
  ctx.SaveChanges();
  </code></pre>