title: Updating Entity Framework many-to-one Relationship
body: <p>I'm trying to update a one-to-many relationship with EntityFramework, but EF won't save the relationship for some reason. I'm using ASP.Net MVC, but that does not seem to matter in this case as the data is received correctly.</p>
  
  <p>I've tried a lot of possible solutions and some tutorials, unfortunately almost all of them describe a scenario where the connection is made via a foreign key property in the class itself.(I'm aware that EF adds a FK in the database, but i cant access that directly.) My approach seems to be significantly different as none of their solution seems to work for me.</p>
  
  <p>The code below seems to me to be the most promising, but it still doesn't work. the foreign key of the activity object doesn't get updated.</p>
  
  <p>Removing <code>context.Entry(act.ActivityGroup).State = EntityState.Detached;</code> causes a Primary Key collision, as EF tries to insert the ActivityGroup as a new Entity. Marking it as <code>Modified</code>, doesn't do the trick either.</p>
  
  <p>Models:</p>
  
  <pre><code>public class Activity
  {
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      [Key]
      public Guid ActivityID { get; set; }
      public string Name { get; set; }
      public ActivityGroup ActivityGroup { get; set; }
  }
  
  
  public class ActivityGroup
  {
      public int ActivityGroupID { get; set; }
      public string GroupName { get; set; }
      public string BackgroundColor { get; set; }
  }
  </code></pre>
  
  <p>Method to save Data</p>
  
  <pre><code>public ActionResult SaveActivities(List&lt;Activity&gt; activities)
  {
      if (ModelState.IsValid)
      {
          using (TSSDBContext context = new TSSDBContext())
          {
              foreach (Activity act in activities)
              {
                  if (act.ActivityGroup != null)
                  {
                        context.Entry(act.ActivityGroup).State = EntityState.Detached;
                  }
                  context.Entry(act).State = (act.ActivityID == null || act.ActivityID == Guid.Empty) ? EntityState.Added : EntityState.Modified;
              }
              context.SaveChanges();
              return new HttpStatusCodeResult(200);
          }
      }else
      {
          return new HttpStatusCodeResult(500);
      }
  
  }
  </code></pre>