在ASP.Net Core 1.1解决方案中检测到自引用循环

时间:2017-05-29 20:02:27

标签: c# asp.net-core json.net object-graph

虽然我已经按照文章here继续收到错误

  

为属性'...'检测到自引用循环,类型为'...'。路径'[4] .... [0]'。

我已将此添加到我的Startup.cs

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

还有什么可能导致参考循环错误?

编辑: 在评论中回答问题...... 受影响的类是:

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 个答案:

答案 0 :(得分:4)

我找到了要添加的解决方案

[JsonIgnore]

受影响财产的注释。但是,我预计在使用ReferenceLoopHandling.Ignore

时不需要这样做

答案 1 :(得分:1)

某些序列化框架不允许这样的循环。例如,如果遇到周期,Json.NET将引发以下异常。

class Foo(generics.ListView):
    context_object_name = 'comments'

如果使用的是ASP.NET Core,则可以将Json.NET配置为忽略它在对象图中找到的循环。这是通过Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'Blog' with type 'MyApplication.Models.Blog'. 中的ConfigureServices(...)方法完成的。

Startup.cs

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