【问题标题】:Self referencing loop detected in ASP.Net Core 1.1 SolutionASP.Net Core 1.1 解决方案中检测到自引用循环
【发布时间】:2017-10-30 04:28:30
【问题描述】:

虽然我已经关注了here 的文章,但我一直收到错误提示

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

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

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

还有什么可能导致引用循环错误?

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

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

【问题讨论】:

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


【解决方案1】:

我找到了添加的解决方案

[JsonIgnore]

对受影响属性的注释。但是,我预计在使用 ReferenceLoopHandling.Ignore 时不需要这样做

【讨论】:

    【解决方案2】:

    一些序列化框架不允许这样的循环。比如Json.NET遇到循环会抛出如下异常。

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

    如果您使用的是 ASP.NET Core,则可以将 Json.NET 配置为忽略它在对象图中找到的循环。这是在Startup.csConfigureServices(...) 方法中完成的。

    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

    【讨论】:

      猜你喜欢
      • 2016-04-17
      • 2017-12-09
      • 2021-01-14
      • 2020-03-29
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多