mJay
mJay

Reputation: 743

Self referencing loop detected in ASP.Net Core 1.1 Solution

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; }
}

Upvotes: 3

Views: 4462

Answers (2)

Adis Azhar
Adis Azhar

Reputation: 1022

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://learn.microsoft.com/en-us/ef/core/querying/related-data

Upvotes: 2

mJay
mJay

Reputation: 743

I found the solution which is to add

[JsonIgnore]

annotation to the affected property. However, I expected that this would not be necessary when using ReferenceLoopHandling.Ignore

Upvotes: 5

Related Questions