EF Core - 循环引用并序列化为 json

ame*_*els 6 entity-framework .net-core

实体示例:

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; }
}
Run Code Online (Sandbox Code Playgroud)

等等。

我从 db 返回 10 个实体,总共有大约 200 条记录。问题是这些实体之间通过 M:M 和 1:M 相互连接,例如,这意味着它们具有循环引用。

我将其映射到一个大对象 DTO 模型,并返回到控制器以在 json 中序列化所有内容。

问题是循环引用,这会导致序列化出现问题。我只谈论 200 条记录,它需要永远,因为它处于无限序列化循环中。

这是否可以通过禁用序列化子对象来解决,或者为每个实体创建新的 DTO,而不包括子对象?

Fab*_*rie 0

我知道 .Net core 包含一个选项来防止循环引用循环。

该选项称为 Newtonsoft.Json.ReferenceLoopHandling.Ignore,必须在 .Net core 中的启动文件上设置。