title: MVC Entity Framework Edit View for a Model with a Foreign Key
body: <p>I have a Project model and a Skill model, </p>
  
  <p>the Project has a one to many relationship to skills</p>
  
  <p>I am having an issue figuring out how to do the edit actionmethod for the Project,</p>
  
  <p>When the project object is instantiated by mvc,  the skill collection is null, in the view I display checkboxes and need to add and remove from this collection</p>
  
  <p>I figure I need to load the Project from the database and then map the modified fields and then save, is this the right way to go about it? is there a better way to do this than doing it manually?</p>
  
  <p>Thanks in advance.</p>
  
  <pre><code>        [HttpPost]
      public ActionResult Edit(Project project)
      {
          if (ModelState.IsValid)
          {
              if (project.Skills == null)
              { 
                  project.Skills = new List&lt;Skill&gt;();
              }
              foreach (var key in Request.Params.AllKeys)
              {
                  if (key.Contains("Skill_"))
                  {
                      if (Request.Params[key].Contains('t'))
                      {
                          var skillId = Convert.ToInt32(key.Split('_')[1]);
                          if (!project.Skills.Any(s =&gt; s.ID == skillId))
                          {
                              project.Skills.Add(db.Skills.Single(s =&gt; s.ID == skillId));
                          }
                      }
                  }
              }
              List&lt;Skill&gt; skillsToRemove = new List&lt;Skill&gt;();
              foreach (var skill in project.Skills)
              {
                  if (!Request.Params["Skill_" + skill.ID.ToString()].Contains('t'))
                  {
                      skillsToRemove.Add(skill);
                  }
              }
              foreach (var skill in skillsToRemove)
              {
                  project.Skills.Remove(skill);
              }
              db.Entry(project).State = EntityState.Modified;
              db.SaveChanges();
              return RedirectToAction("Index");
          }
          ViewBag.Skills = db.Skills.ToList();
          return View(project);
      }
  </code></pre>