Entity Framework 6.1.3 foreign key set to null on self referencing table
<p>I am using a generic repository in a code first model with Entity Framework 6.1.3 and all has been working well ... until now. I want to update many records simultaneously and have the following code:</p>

<pre><code>public T[] UpdateMany&lt;T&gt;(params T[] entities) where T : class
{            
   foreach (T item in entities)
   {
       var entry = _context.Entry(item);
       _context.Set&lt;T&gt;().Attach(item);
       entry.State = EntityState.Modified;
    }                 

    return entities;
}
</code></pre>

<p>Once this has ran I save the changes accordingly and so only hit the database with my updates once. So far so good but then I passed it an array of entities of a type that contains a self referencing foreign key. So, <code>Foo</code> contains a <code>ParentId</code> which references the primary key (<code>Id</code>) in the same entity. </p>

<pre><code>public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public string Node { get; set; }
    public bool IsActive{ get; set; }

    public virtual Foo Parent { get; set; }
    public virtual ICollection&lt;Foo&gt; Children{ get; set; }
}
</code></pre>

<p>The array I pass in will include items that reference each other. I might want to set the <code>isActive</code> field to true for a handful of <code>Foo</code>'s. Something like:</p>

<pre><code>[
   { id: 1, parentId: null, name: "foo 1", isActive: true},
   { id: 2, parentId: 1, name: "foo 2", isActive: true},
   { id: 3, parentId: 2, name: "foo 3", isActive: true},
   { id: 4, parentId: 2, name: "foo 4", isActive: true},
]
</code></pre>

<p>The problem comes when the first item hits the line. </p>

<pre><code>var entry = _context.Entry(item);
</code></pre>

<p>The rest of the items in the array then have their <code>parentId</code> set to null (this field needs to be nullable to establish a root) breaking the relationship!</p>

<p>I've tried reversing the order the items are passed in but that didn't work. The only workaround I've got is to save on each loop but the performance obviously deteriorates the bigger the array. </p>

<p>I've not managed to find anyone else experiencing this problem. Maybe there's something fundamental missing from my understanding of Entity Framework.</p>

<p>Can anyone help? It's driving me mad!</p>