1

I have an API which is producing some interesting results. When debugging, the everything is as expected till serialization.

The ScheduleEvent entity has a foreign key to the Project entity. I'm trying to return all ScheduleEvents which match a given id.

When I run the below, it returns the correct result, but if it should return 10 entries, it returns 10^2 (correct result 10 times over).

return Ok(await _context.ScheduleEvent.Include(m => m.Project)
                .Where(x => x.Project.ProjectName == id).ToListAsync());

Originally the command below resulted in the self referencing loop detected error. I added the below which resolves the error.

services.AddMvc().AddJsonOptions(options =>
{
    //options.SerializerSettings.NullValueHandling = 
    //              Newtonsoft.Json.NullValueHandling.Include;

    options.SerializerSettings.ReferenceLoopHandling = 
                  Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

If I run the below, it outputs as expected.

return Ok(await _context.Project.Include(p => p.ScheduleEvents)
               .Where(x => x.ProjectName == id).ToListAsync());

Code for the models:

Project

public class Project
{
    [Key]
    public int ProjectId { get; set; }
    public string ProjectName { get; set; }

    ...

    public ICollection<ScheduleEvent> ScheduleEvents { get; set; } = null;
}

ScheduleEvent

public class ScheduleEvent
{
    [Key]
    [JsonProperty("ScheduleEventId")]
    public int ScheduleEventId { get; set; }

    ...

    [Display(Name = "Project")]
    [JsonProperty("Project")]
    [ForeignKey("ProjectForeignKey")]
    public virtual Project Project { get; set; } = null;
}
2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.