title: Preventing StackOverflowException while serializing Entity Framework object graph into Json
body: <p>I want to serialize an <a href="http://blogs.msdn.com/b/efdesign/archive/2009/03/24/self-tracking-entities-in-the-entity-framework.aspx" rel="nofollow noreferrer">Entity Framework Self-Tracking Entities</a> full object graph (parent + children in one to many relationships) into Json.</p>
  
  <p>For serializing I use <strong>ServiceStack.JsonSerializer</strong>.</p>
  
  <p>This is how my database looks like (for simplicity, I dropped all irrelevant fields):</p>
  
  <p><img src="https://i.stack.imgur.com/gbKDg.gif" alt="ERD"></p>
  
  <p>I fetch a full profile graph in this way:</p>
  
  <pre><code>public Profile GetUserProfile(Guid userID)
  {
      using (var db = new AcmeEntities())
      {
          return db.Profiles.Include("ProfileImages").Single(p =&gt; p.UserId == userId);
      }
  }
  </code></pre>
  
  <p>The problem is that attempting to serialize it:</p>
  
  <pre><code>Profile profile = GetUserProfile(userId);
  ServiceStack.JsonSerializer.SerializeToString(profile);
  </code></pre>
  
  <p>produces a <code>StackOverflowException</code>.
  I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: <code>profile.ProfileImages[0].Profile.ProfileImages[0].Profile ...</code> and so on.</p>
  
  <p>How can I "flatten" my EF object graph or otherwise prevent <strong>ServiceStack.JsonSerializer</strong> from running into stack overflow situation?</p>
  
  <p><em>Note:</em> I don't want to project my object into an anonymous type (like <a href="https://stackoverflow.com/a/7611766/290343">these</a> <a href="https://stackoverflow.com/a/658056/290343">suggestions</a>) because that would introduce a very long and hard-to-maintain fragment of code).</p>