title: How to update related entities in Entity Framework
body: <p>I have an MVC project and using Entity Framework Code First and POCO objects for the database. For example:</p>
  
  <pre><code>public class ClassA
  {
    public int? Id {get; set;}
    public string Name { get; set;}
    public virtual ClassB B {get; set;}
  }
  
  public class ClassB
  {
    public int? Id {get;set;}
    public string Description {get;set;}
  }
  </code></pre>
  
  <p>I have an ActionResult that create or edit a model. The problem is when I call this ActionResult to update the model, and <code>model.B</code> has been changed, the relation is not saved in the database. When the ActionResult is called to create a new object it works as expected. How do I solve this?</p>
  
  <pre><code>public ActionResult Save(ClassA model)
  {
    model.B = GetBFromDb(model.B.Id.Value);
  
    if(ModelState.IsValid)
    {
      if (id.HasValue)
      {
        context.Entry(model).State = System.Data.EntityState.Modified;
      }
      else
      {
        context.ClassAs.Add(model);
      }
      context.SaveChanges();
      // redirect to index etc.
    }
    return View("EditForm", model);
  }
  </code></pre>