title: How to prevent cyclic loading of related entities in Entity Framework Code First
body: <p>I'm new to Entity Framework and am trying to learn how to use Code First to load entities from the database. </p>
  
  <p>My model contains a user:</p>
  
  <pre><code>public class User
  {
      public int UserID { get; set; }
  
      [Required]
      public string Name { get; set; }
  
      // Navigation Properties
      public virtual ICollection&lt;AuditEntry&gt; AuditEntries { get; set; }
  }
  </code></pre>
  
  <p>Each user can have a set of audit entries each of which contains a simple message:</p>
  
  <pre><code>public class AuditEntry
  {
      public int AuditEntryID { get; set; }
  
      [Required]
      public string Message { get; set; }
  
      // Navigation Properties
      public int UserID { get; set; }
      public virtual User User { get; set; }
  }
  </code></pre>
  
  <p>I have a DBContext which just exposes the two tables:</p>
  
  <pre><code>public DbSet&lt;User&gt; Users { get; set; }
  public DbSet&lt;AuditEntry&gt; AuditEntries { get; set; }
  </code></pre>
  
  <p>What I want to do is load a list of AuditEntry objects containing the message and the related User object containing the UserID and Name properties. </p>
  
  <pre><code>List&lt;AuditEntry&gt; auditEntries = db.AuditEntries.ToList();
  </code></pre>
  
  <p>Because I have my navigation properties marked as virtual and I haven't disabled lazy loading, I get an infinitely deep object graph (each AuditEntry has a User object, which contains a list of the AuditEntries, each of which contains a User object, which contains a list of AuditEntries etc)</p>
  
  <p>This is no good if I then want to serialize the object (for example to send as the result in a Web API).</p>
  
  <p>I've tried turning off lazy loading (either by removing the virtual keywords from my navigation properties in the model, or by adding this.Configuration.LazyLoadingEnabled = false; to my DBContext). As expected this results in a flat list of AuditEntry objects with User set to null.</p>
  
  <p>With lazy loading off, I've tried to eager load the User like so:</p>
  
  <pre><code>var auditentries = db.AuditEntries.Include(a =&gt; a.User);
  </code></pre>
  
  <p>but this results in the same deep / cyclic result as before.</p>
  
  <p>How can I load one level deep (e.g. include the user's ID and name) without also loading back-references / following navigation properties back to the original object and creating a cycle?</p>