JSON.NET Error Self referencing loop detected for type

后端 未结 25 2959
我在风中等你
我在风中等你 2020-11-22 02:16

I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject 

25条回答
  •  無奈伤痛
    2020-11-22 02:30

    If you're using .NET Core 2.x, update your ConfigureServices section in Startup.cs

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

        public void ConfigureServices(IServiceCollection services)
        {
        ...
    
        services.AddMvc()
            .AddJsonOptions(
                options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );
    
        ...
        }
    

    If you're using .NET Core 3.x without MVC, it would be:

    services.AddControllers()
      .AddNewtonsoftJson(options =>
          options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
       );
    

    This reference loop handling is almost mandatory if you're using Entity Framework and database-first design pattern.

提交回复
热议问题