title: Entity Framework 6: Adding child object to parent's list vs. setting child's navigation property to parent
body: <p>I have an existing database with two tables <code>MailServers</code> and <code>MailDomains</code> in it. <code>MailDomains</code> has the foreign key column <code>MailServerId</code> pointing to the <code>Id</code> primary key column in <code>MailServers</code>. So we have a one-to-many-relationship here.</p>
  
  <p>I followed <a href="http://msdn.microsoft.com/en-gb/data/jj200620.aspx" rel="noreferrer">this article</a> and created my Entity Framework POCOs via the "Code first from database" model in the Entity Data Model Wizard. This produced the following two C# classes:</p>
  
  <pre><code>public partial class MailServer
  {
      public MailServer()
      {
          MailDomains = new HashSet&lt;MailDomain&gt;();
      }
  
      public int Id { get; set; }
  
      public virtual ICollection&lt;MailDomain&gt; MailDomains { get; set; }
  }
  
  
  
  public partial class MailDomain
  {
      public MailDomain()
      {
      }
  
      public int Id { get; set; }
  
      public string DomainName { get; set; }
  
      public int MailServerId { get; set; }
      public virtual MailServer MailServer { get; set; }
  }
  </code></pre>
  
  <p>Now my question is whether there is any difference between the following two approaches of creating and inserting new objects to the database.</p>
  
  <p>Approach (A): Adding new child to the parent's list:</p>
  
  <pre><code>        var mailServer = new MailServer();
          var mailDomain = new MailDomain() {
              DomainName = "foobar.net",
          };
          mailServer.MailDomains.Add(mailDomain);
  
          using(var context = new MyContext){
              context.MailServers.Add(mailServer);
              context.SaveChanges();
          }
  </code></pre>
  
  <p>Approach (B): Setting the child's navigation property to the parent:</p>
  
  <pre><code>        var mailServer = new MailServer();
          var mailDomain = new MailDomain() {
              DomainName = "foobar.net",
              MailServer = mailServer,
          };
  
          using(var context = new MyContext){
              context.MailDomains.Add(mailDomain);
              context.SaveChanges();
          }
  </code></pre>
  
  <p>I also assume that in approach (A) the new <code>MailDomain</code> instance is automatically added to the collection <code>context.MailDomains</code> while in approach (B) the new <code>MailServer</code> instance is automatically added to the collection <code>context.MailServers</code>. Is that correct or do I have to do that manually?</p>
  
  <p>So again, my question is: are the two approaches interchangeable?
  It just confuses me that in the database there is only one property/column to set (namely the foreign key in <code>MailDomains</code>) while in the C# code there are two properties (one in each class) that could be modified.</p>