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?
To preserve references and handle circular references, set ReferenceHandler to Preserve. This setting causes the following behavior: On serialize: When writing complex types, the serializer also writes metadata properties ( $id , $values , and $ref ).
Specifies the settings on a JsonSerializer object.
Notice the navigation property check boxes, you can deselect them if you don't want them to be generated. To solve your circular reference problem, make sure only one or none are checked, not both.
Ignore individual properties You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored. If no Condition is specified, this option is assumed.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With