title: How do I prevent InvalidOperationException saving a cyclic graph of entities?
body: <p>Given the entities,</p>
  
  <pre><code>class A {
      B DefaultB { get; set; }
      C DefaultC { get; set; }
  }
  
  class B {
      A { get; set; }
  }
  
  class C {
      A { get; set; }
  }
  </code></pre>
  
  <p>where <code>A.DefaultB</code> and <code>A.DefaultC</code> are optional,</p>
  
  <pre><code>modelBuilder.Entity&lt;A&gt;().HasOptional(x =&gt; x.DefaultB).WithMany();
  modelBuilder.Entity&lt;A&gt;().HasOptional(x =&gt; x.DefaultC).WithMany(); 
  </code></pre>
  
  <p>what combination of <code>context.Set&lt;T&gt;().Add(...)</code> and <code>context.SaveChanges()</code> would work to save the following object graph?</p>
  
  <pre><code>var b = new B();
  var c = new C();
  var a = new A { DefaultB = b, DefaultC = c, };
  b.A = a;
  c.A = a;
  // now save these...
  </code></pre>
  
  <p>As it is now, I get an <code>InvalidOperationException</code> (collection modification while iterating) because EF <a href="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/39797e39-0dec-4957-bca5-8176fe27b94a" rel="nofollow">does not seem to handle cycles very well</a>.</p>