title: .NET Core, circular references on particular entity using XMLParser
body: <p>I am using C# .Net Core along with the XMLSerializer, I've checked various other questions but none of the provided answers seem to work for me. I Have a MaintenanceMoment that has multiple time blocks, so a one-to-many relation, I've created it like the following:</p>
  <p>My Model code:</p>
  <p><code>PRMaintenanceMoment.cs</code></p>
  <pre><code>    public class PRMaintenanceMoment
      {
        [XmlIgnore]
        public int ID { get; set; }
  
        [Required]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = &quot;{0:yyyy-MM-dd}&quot;)]
        public string EarliestExecutionDate { get; set; }
  
        [Required]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = &quot;{0:yyyy-MM-dd}&quot;)]
        public string LatestExecutionDate { get; set; }
  
        public List&lt;Timeblock&gt; Timeblock { get; set; } = new List&lt;Timeblock&gt;();
      }
  </code></pre>
  <p><code>Timeblock.cs</code></p>
  <pre><code>public class Timeblock
  {
      [XmlIgnore]
      public int ID { get; set; }
  
      [ForeignKey(&quot;MaintenanceMomentID&quot;)]
      public PRMaintenanceMoment MaintenanceMoment { get; set; }
  
      [Required]
      [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = &quot;{0:hh:mm:ss}&quot;)]
      public DateTime EarliestExecutionTime { get; set; }
  
      [Required]
      [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = &quot;{0:hh:mm:ss}&quot;)]
      public DateTime LatestExecutionTime { get; set; }
  }
  </code></pre>
  <p>The reference in my Database Context has been made like this:
  <code>ApplicationDbContext.cs</code></p>
  <pre><code>public class ApplicationDbContext : DbContext
  {
      public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options)
          : base(options) { }
  
      public DbSet&lt;Timeblock&gt; Timeblocks { get; set; }
  
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
          modelBuilder.Entity&lt;PRMaintenanceMoment&gt;()
              .HasMany(tb =&gt; tb.Timeblock)
              .WithOne(pr =&gt; pr.MaintenanceMoment);
   }
  }
  </code></pre>
  <p>My Controller that servers the MaintenanceMoment is created like so (I've excluded the generic repo &amp; interface as they don't matter for this example):</p>
  <p><code>PRMaintenanceMoment.cs</code></p>
  <pre><code>    public class PRMaintenanceMomentRepository : GenericRepository&lt;PRMaintenanceMoment&gt;, IPRMaintenanceMomentRepository
  {
      public PRMaintenanceMomentRepository(ApplicationDbContext context)
          : base(context) { }
  
      public override List&lt;PRMaintenanceMoment&gt; Index()
      {
          var context = _context.PRMaintenanceMoments
                 .Include(PRMaintenanceMoment =&gt; PRMaintenanceMoment.Timeblock)
              .ToList();
  
          return context;
      }
  
      public void Update(int id, PRMaintenanceMoment maintenanceMoment)
      {
          PRMaintenanceMoment DBPRMaintenanceMoment = _context.PRMaintenanceMoments.FirstOrDefault(ms =&gt; ms.ID.Equals(id));
  
          _context.Entry&lt;PRMaintenanceMoment&gt;(DBPRMaintenanceMoment).CurrentValues.SetValues(maintenanceMoment);
  
          _context.SaveChanges();
      }
  }
  </code></pre>
  <p>The eventual Migration that is created shows the following:</p>
  <pre><code>migrationBuilder.CreateTable(
              name: &quot;PRMaintenanceMoments&quot;,
              columns: table =&gt; new
              {
                  ID = table.Column&lt;int&gt;(nullable: false)
                      .Annotation(&quot;MySql:ValueGenerationStrategy&quot;, 
                       MySqlValueGenerationStrategy.IdentityColumn),
                  EarliestExecutionDate = table.Column&lt;string&gt;(nullable: false),
                  LatestExecutionDate = table.Column&lt;string&gt;(nullable: false)
              },
              constraints: table =&gt;
              {
                  table.PrimaryKey(&quot;PK_PRMaintenanceMoments&quot;, x =&gt; x.ID);
              });
  
          migrationBuilder.CreateTable(
              name: &quot;Timeblocks&quot;,
              columns: table =&gt; new
              {
                  ID = table.Column&lt;int&gt;(nullable: false)
                      .Annotation(&quot;MySql:ValueGenerationStrategy&quot;, MySqlValueGenerationStrategy.IdentityColumn),
                  MaintenanceMomentID = table.Column&lt;int&gt;(nullable: true),
                  EarliestExecutionTime = table.Column&lt;DateTime&gt;(nullable: false),
                  LatestExecutionTime = table.Column&lt;DateTime&gt;(nullable: false)
              },
              constraints: table =&gt;
              {
                  table.PrimaryKey(&quot;PK_Timeblocks&quot;, x =&gt; x.ID);
                  table.ForeignKey(
                      name: &quot;FK_Timeblocks_PRMaintenanceMoments_MaintenanceMomentID&quot;,
                      column: x =&gt; x.MaintenanceMomentID,
                      principalTable: &quot;PRMaintenanceMoments&quot;,
                      principalColumn: &quot;ID&quot;,
                      onDelete: ReferentialAction.Restrict);
              });
  
          migrationBuilder.CreateIndex(
              name: &quot;IX_PlanningRequests_PRMaintenanceMomentID&quot;,
              table: &quot;PlanningRequests&quot;,
              column: &quot;PRMaintenanceMomentID&quot;);
  
          migrationBuilder.CreateIndex(
              name: &quot;IX_Timeblocks_MaintenanceMomentID&quot;,
              table: &quot;Timeblocks&quot;,
              column: &quot;MaintenanceMomentID&quot;);
  </code></pre>
  <p>Which seems quite alright to me, then, as many questions suggest is adding the <code>ReferenceLoopHandling</code> from the JSON serializer. I've tried this but this didn't seem to help. For completion's sake, I've added the most important bits of my startup.cs file; this is of course not the full file, but the most important settings.</p>
  <p><code>startup.cs</code></p>
  <pre><code>    public void ConfigureServices(IServiceCollection services)
      {
          services.AddControllers()
               .AddXmlSerializerFormatters(); // Adding the XML serializer here
  
          services.AddMvc(options =&gt;
          {
              options.MaxValidationDepth = 64;
              options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
              options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
          });
  
  services.AddMvc().AddNewtonsoftJson(jsonOptions =&gt; { jsonOptions.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;  });
  
  Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  }
  
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          app.UseRouting();
          app.UseAuthentication();
          app.UseAuthorization();
  
          app.UseEndpoints(endpoints =&gt;
          {
              endpoints.MapControllers();
          });
      }
  </code></pre>
  <p>Finally the exact error thrown is:</p>
  <pre><code>System.InvalidOperationException: There was an error generating the XML document.
  ---&gt; System.InvalidOperationException: A circular reference was detected while serializing an object of type SALES005.Models.PRMaintenanceMoment.
  at System.Xml.Serialization.XmlSerializationWriter.WriteStartElement(String name, String ns, Object o, Boolean writePrefixed, XmlSerializerNamespaces xmlns)
  at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write3_PRMaintenanceMoment(String n, String ns, PRMaintenanceMoment o, Boolean isNullable, Boolean needType)
  at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write2_Timeblock(String n, String ns, Timeblock o, Boolean isNullable, Boolean needType)
  at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write3_PRMaintenanceMoment(String n, String ns, PRMaintenanceMoment o, Boolean isNullable, Boolean needType)
  at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write4_ArrayOfPRMaintenanceMoment(Object o)
  </code></pre>