title: Need to understand Entity Framework reference states
body: <p>I am implementing the entity framework for the first time.  I am working with adding/updating objects that have a parent property.</p>
  
  <p>I am aware that the parent entity of an entity is initialized as "null".  I do not have a full understanding of how to use the parent entity vs. the parent entity reference fields, or what is required to be able to save the changes to an entity.</p>
  
  <ol>
  <li>Am I missing any important factors in my analysis (i.e. EntityState?)</li>
  <li>Which of the following situations are possible, and </li>
  <li>What is the best method for dealing with them:</li>
  </ol>
  
  <p>Entity: null<br/>
  EntityReference: not null</p>
  
  <p>Entity: not null<br/>
  EntityReference: null</p>
  
  <p>Entity: not null<br/>
  EntityReference: not null</p>
  
  <p>Thank you for any help.</p>
  
  <p>code sample:</p>
  
  <pre><code>internal void AddUpdateObject(MyDataContext context)
  {
  // HOW DO I HANDLE THIS SECTION vvvv
  if (this.MyParentEntity == null)
  {
      throw new Exception("Parent Property Null.");
  }
  if (this.MyParentEntity.EntityState == EntityState.Detached)
  {
      MyParentEntity t = this.MyParentEntity;
      this.MyParentEntity = null;
      context.AttachTo("ParentCollection", t);
      this.MyParentEntity = t;
  }
  // ^^^^^^^^^
  try
  {
      context.AddToMyEntities(this);
  }
  catch (InvalidOperationException)
  {
      // the object with the key already exists
      MyEntity ent = context.MyEntities.First(x =&gt; x.id == this.id);
      PropertyInfo[] props = typeof(MyEntity).GetProperties();
      foreach (PropertyInfo pi in props)
      {
          if (pi.CanRead &amp;&amp; pi.CanWrite &amp;&amp;
              !pi.PropertyType.Name.StartsWith("EntityCollection") &amp;&amp;
              !pi.Name.Equals("id"))
              pi.SetValue(ent, pi.GetValue(this, null), null);
      }
  }
  }
  </code></pre>