EF Core - circular reference and serializing to json

旧城冷巷雨未停 提交于 2021-01-27 07:34:56

问题


Example of entities:

public class HistoryWorkoutExercise : EntityMaximum
{
    /// <summary>
    /// Gets or sets the Weight.
    /// </summary>
    public decimal? Weight { get; set; }

    /// <summary>
    /// Gets or sets the Speed.
    /// </summary>
    public decimal? Speed { get; set; }

    /// <summary>
    /// Gets or sets the Time.
    /// </summary>
    public decimal? Time { get; set; }

    public int NumberOfRepetitions { get; set; }
    public int NumberOfCompletedRepetitions { get; set; }
    public int ExerciseId { get; set; }
    public Exercise Exercise { get; set; }
    public int HistoryWorkoutId { get; set; }
    public HistoryWorkout HistoryWorkout { get; set; }
}

public class Exercise : EntityMaximum
{
    public string Name { get; set; }
    public byte Type { get; set; }
    public string VideoUrl { get; set; }
    public bool IsEquipment { get; set; }
    public bool IsTimed { get; set; }
    public bool IsSpeed { get; set; }

    public ICollection<WorkoutExercise> WorkoutExercises { get; set; }
    public ICollection<HistoryWorkoutExercise> HistoryWorkoutExercises { get; set; }
}

etc.

I am returning 10 entities from db, with around 200 records in total. Problem is that those entities are connected between each other with M:M and 1:M for example, which means they have circular reference.

I map this to one big object DTO model, and return to controller to serialize all in json.

Problem is circular reference, which causes troubles with serialization. I am talking about 200 records only, and it takes forever because it is in infinite serialization loop.

Can this be resolved by disabling serializing child objects, or create new DTO for each entity, with not including child objects?


回答1:


This worked for me. Add this on startup.cs of the .net core app.

services
.AddMvc()
.AddJsonOptions(opt =>
{
opt.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});



回答2:


I know that .Net core include an option to prevent to loop on circular references.

The option is called Newtonsoft.Json.ReferenceLoopHandling.Ignore and must be setup on startup file in .Net core.



来源:https://stackoverflow.com/questions/48875542/ef-core-circular-reference-and-serializing-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!