title: Remove cyclic references from Automapper for Rest responses from EF
body: <p>I have an m:n relationship between 2 entities:</p>
  <p>Person (id, name, ...), PersonJob (personid, jobid), Job (id, jobname, ...)</p>
  <p>I can easly read my data from EF, map it via Automapper and return it as a REST api result like this (Dto being my Data Transfer Obects for the api calls):</p>
  <pre><code>public class MappingProfile : Profile {
      public MappingProfile() {
          CreateMap&lt;Person, PersonDto&gt;();
          CreateMap&lt;PersonJob , PersonJobDto&gt;();
          CreateMap&lt;Job, JobDto&gt;();
  ...
  
  public async Task&lt;PersonDto?&gt; GetPersonDetailsAsync(long id)
  {
      var person = await context.Persons
          .Include(x =&gt; x.PersonJob ).ThenInclude(x =&gt; x.Job)
          .SingleOrDefaultAsync(p =&gt; p.Id == id);
  
      return person == null ? null : mapper.Map&lt;Person, PersonDto&gt;(person );
  }
  
  public async Task&lt;JobDto?&gt; GetJobDetailsAsync(long id)
  {
      var job = await context.Jobs
          .Include(x =&gt; x.PersonJob ).ThenInclude(x =&gt; x.Person)
          .SingleOrDefaultAsync(p =&gt; p.Id == id);
  
      return job == null ? null : mapper.Map&lt;Job, JobDto&gt;(job);
  }
  </code></pre>
  <p>The Mapper works pretty nice, handling the cyclic nature of the EF objects pretty well. A Person object contains multiple PersonJob objects. These have a reference back to the object and a reference to the Job, which itself has a reference back to the PersonJob object.</p>
  <p>But when I pass this data back via the REST interface this all gets serialized in a HUGE json string. So the Person contains a PersonJob that contains the original Person that contains the same PersonJob, ...</p>
  <p>I cannot add the fields as Ignore fields in the mapping as I need both &quot;mapping directions&quot; - coming from Person to Job and from Job to Person.</p>
  <p>At the moment I am deleting the &quot;back references&quot; after the Mapping, but this is obviosly not a good solution and hard to maintain if the object structures are more complex.</p>
  <p>Is there an elegant way?</p>
  <p>regards,
  Christoph</p>