title: The merge statement conflicted with the foreign key while inserting self join tables
body: <p>I have two entities:</p>
  <pre><code>public class Header 
  {
          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
          [Key]
          public int Id {get;set;} 
          public string RefNo { get; set; }           
          public decimal TotalAmount { get; set; }
          public ICollection&lt;Detail&gt; Detail { get; set; }
  }
  
  public class Detail 
  {        
           [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
           [Key]
           public int Id {get;set;} 
           public int HeaderId { get; set; }
           public decimal Amount { get; set; } 
           public int? ParentDetailId { get; set; }     
           public virtual Detail ParentDetail { get; set; }
           public virtual ICollection&lt;Detail&gt; ChlidDetail { get; set; }            
  }
  </code></pre>
  <p>If there is one header and multiple details with out child details it is working fine, but when trying to insert a <code>ChildDetail</code>, I get an error.</p>
  <p>This is how I am trying to insert:</p>
  <pre><code> Header hdr = new Header();
   hdr.RefNo = &quot;Test&quot;;
   hdr.TotalAmount  = Convert.ToDecimal(5.3);
   hdr.Detail = new List&lt;Detail&gt;();
   hdr.Detail.Add(new Detail
                      {
                          HeaderId = hdr.Id,
                          Amount = 50,             
                          ParentDetail = null,            
                          ChlidDetail = new List&lt;Detail&gt;()
                      });
  
  foreach(var dtl in hdr.Detail)
  {
      dtl.ChlidDetail.Add(new Detail { HeaderId = hdr.Id, Amount = 25, ParentDetailId = dtl.Id });
  }
  </code></pre>
  <p>After adding all entities called <code>context.SaveChanges()</code> and I get an error:</p>
  <blockquote>
  <p>The MERGE statement conflicted with the FOREIGN KEY constraint
  &quot;FK_Detail_Header_HeaderId&quot;. The conflict occurred in database &quot;XXXX&quot;,
  table &quot;dbo.Header&quot;, column 'Id'</p>
  </blockquote>
  <p>This is how the context code is there(using repository pattern)</p>
  <p>here is the code snippet of context layer</p>
  <pre><code>internal readonly ApiContext context;
  internal DbSet&lt;T&gt; entities;
  string errorMessage = string.Empty;
  
  public Repository(ApiContext context)
      {
          this.context = context;
          entities = context.Set&lt;T&gt;();
      }
  
      
   public T Insert(T entity)
     {
        if (entity == null)
           {
              throw new ArgumentNullException(&quot;entity&quot;);
           }
       entities.Add(entity);
       context.SaveChanges();
       return entity;          
     }
  
      
  </code></pre>