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

时间:2018-02-19 23:10:24

标签: 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; }
}

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

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

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

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

2 个答案:

答案 0 :(得分:1)

这对我有用。将此添加到.net核心应用程序的startup.cs上。

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

答案 1 :(得分:0)

我知道.Net核心包含一个选项,可以防止循环引用循环。

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