EF Core-循环引用并序列化为json [英] EF Core - circular reference and serializing to json

查看:38
本文介绍了EF Core-循环引用并序列化为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体示例:

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相互连接,这意味着它们具有循环引用.

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.

我将此映射到一个大对象DTO模型,然后返回到控制器以序列化json中的所有内容.

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

问题是循环引用,这会导致序列化麻烦.我只在说200条记录,它要花很多时间,因为它处于无限序列化循环中.

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.

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

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

推荐答案

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

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;
});

这篇关于EF Core-循环引用并序列化为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆