title: Avoid or control circular references in Entity Framework Core
body: <p>I really am done with this, but at least I want to know what's going on. Here we go:</p>
  <p>My project is an ASP.NET Core Web Application with Code First Entity Framework Core and an Angular frontend.</p>
  <p>I want to control when to load referenced objects. They can be useful, but they can also create circular references with internal errors on the frontend. (JSON would be infinitely long.)</p>
  <p>Models:</p>
  <pre><code>class Book {
     public virtual ICollection&lt;Page&gt; Pages { get; set; }
     ...simple properties
  }
  
  class Page {
     public virtual Book Book { get; set; }
     ...simple properties
  }
  </code></pre>
  <br/>
  <p>In this example, every book from <em>books</em> will have an empty/null <em>Pages</em> list.</p>
  <pre><code>using (var context = new MoneyStatsContext())
  {
     var books = context.Books.Where(rule =&gt; rule.State == 1).ToList();
  }
  </code></pre>
  <br/>
  <p>In this example, the <em>Pages</em> lists are not null, and every <em>Page</em> will have it's <em>Book</em> property set. Thus creating a circular reference.</p>
  <pre><code>using (var context = new MoneyStatsContext())
  {
     var books = context.Books.Where(rule =&gt; rule.State == 1).Include(x =&gt; x.Pages).ToList();
  }
  </code></pre>
  <br/>
  <p>How do I avoid the circular reference? Do I really have no other (simpler) choice than creating a new model and manually specifying each property?</p>
  <pre><code>.Select(new Book() {
     ...setting each property by hand
  }
  </code></pre>
  <br/>
  <p><strong>Not-working-solutions I've found:</strong></p>
  <ul>
  <li>Tried setting this false and true. Doesn't seem to change anything.</li>
  </ul>
  <pre><code>public MyContext()
  {
     this.ChangeTracker.LazyLoadingEnabled = false;
  }
  </code></pre>
  <br/>
  <ul>
  <li>Tried specifying this in Startup.cs, but <em>options</em> doesn't have a SerializerSettings property.</li>
  </ul>
  <pre><code>services.AddMvc().AddJsonOptions(options =&gt;
  {
     options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  });
  </code></pre>
  <br/>
  <p>Any help would be appreciated. Thanks in advance.</p>