Self referencing loop detected in ASP.Net Core 1.1 Solution

Viewed 4124

Though I have followed the article here I keep getting the error

self referencing loop detected for property '...' with type '...'. Path '[4]....[0]'.

I have added this to my Startup.cs:

services.AddMvc()
    .AddJsonOptions(opt => 
        opt.SerializerSettings.ReferenceLoopHandling = 
            ReferenceLoopHandling.Ignore
    );

What else could cause the reference loop error ?

EDIT: Answer to question in comments... The affected classes are:

public partial class GuidingSymptom
    {
        public GuidingSymptom()
        {
            VideosGuidingSymptoms = new HashSet<VideosGuidingSymptoms>();
        }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [MaxLength(70)]
        [Required]
        public string Name { get; set; }
        public string Description { get; set; }

        public int SeverityId { get; set; }
        public int? DiagnoseId { get; set; }

        [InverseProperty("GuidingSymptom")]
        public virtual ICollection<VideosGuidingSymptoms> VideosGuidingSymptoms { get; set; }
        [ForeignKey("DiagnoseId")]
        [InverseProperty("GuidingSymptom")]
        public virtual Diagnose Diagnose { get; set; }
        [ForeignKey("SeverityId")]
        [InverseProperty("GuidingSymptom")]
        public virtual GuidingSymptomSeverity Severity { get; set; }
    }

public partial class VideosGuidingSymptoms
{
    public int VideoId { get; set; }
    public int GuidingSymptomId { get; set; }

    [ForeignKey("GuidingSymptomId")]
    [InverseProperty("VideosGuidingSymptoms")]
    public virtual GuidingSymptom GuidingSymptom { get; set; }
    [ForeignKey("VideoId")]
    [InverseProperty("VideosGuidingSymptoms")]
    public virtual Video Video { get; set; }
}
2 Answers

Some serialization frameworks do not allow such cycles. For example, Json.NET will throw the following exception if a cycle is encountered.

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'Blog' with type 'MyApplication.Models.Blog'.

If you are using ASP.NET Core, you can configure Json.NET to ignore cycles that it finds in the object graph. This is done in the ConfigureServices(...) method in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}

https://docs.microsoft.com/en-us/ef/core/querying/related-data

Related