title: _Context.SaveChanges Reset foreign key values in other table
body: <p>for my system, every project can have a limited number of students (1 to M), so when I add or edit a student I always check against the database to check if max the number of students has been reached and if so, I will set a project property IsAvailable to false.
  When I do so, all students Project IDs in the student table turn null, I have been trying to solve for a while, but I can't figure out the reason why is this happening.
  Here is my code</p>
  
  <pre><code>if (await TryUpdateModelAsync&lt;Student&gt;(
          student,
          "student",
          s =&gt; s.Pnumber, s =&gt; s.CourseId, s =&gt; s.ProjectId, s =&gt; s.SupervisorId,
          s =&gt; s.SecondMarkerId, s =&gt; s.FirstName, s =&gt; s.LastName))
          {
              if (student.CourseId == null)
              {
                  ModelState.AddModelError("student.CourseId", "Please Enter the Course of study");
                  return Page();
              }
  
              await _Context.SaveChangesAsync();
  
              List&lt;Project&gt; Projects = (from pr in _Context.Project
                                        select pr).ToList();
              Projects = UpdateAvailability(Projects);
              foreach (var project in Projects)
              {
                  await TryUpdateModelAsync&lt;Project&gt;(project);
                  await _Context.SaveChangesAsync();
              }                
              await TryUpdateModelAsync&lt;User&gt;(User);
              User.Email = student.Pnumber + "@my365.dmu.ac.uk";
              await _Context.SaveChangesAsync();                
              return RedirectToPage("./AllStudents");
          }
  </code></pre>
  
  <p>The UpdateAvailability function:</p>
  
  <pre><code>public List&lt;Project&gt; UpdateAvailability(List&lt;Project&gt; Projects)
      {
          foreach (var project in Projects)
          {
              List&lt;Student&gt; Students = (from st in _Context.Student
                                        where st.ProjectId == project.ProjectId
                                        select st).ToList();
  
              if (Students.Count == project.NumberOfStudents)
              {
                  project.IsAvailable = false;
              }
              else if (Students.Count &lt; project.NumberOfStudents)
              {
                  project.IsAvailable = true;
              }
          }
          return Projects;
      }
  </code></pre>