实体框架自引用类

时间:2021-07-16 15:22:00

标签: c# json api entity-framework

我有一堂这样的课

public class Unit
{
    public int Id { get; set; }
    [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "RequiredMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
    [MaxLength(30, ErrorMessageResourceName = "MaxLengthMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
    [RegularExpression(@"[\u0020\u200C‌\u202F\u0622\u0627\u0628\u067E\u062A\u062B\u062C\u0686\u062D\u062E\u062F\u0630\u0631\u0632\u0698\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\u0641\u0642\u06A9\u06AF\u0644\u0645\u0646\u0648\u0647\u06BE\u06CC\u0643\u064A\u0626]+", ErrorMessageResourceName = "RegularExpressionMessage", ErrorMessageResourceType = typeof(BankPhonesTextResource))]
    public string Name { get; set; }
    public int UnitTypeId { get; set; }
    public UnitType UnitType { get; set; }
    public int? ParentUnitId { get; set; }
    public Unit ParentUnit { get; set; }
    public virtual ICollection<Unit> SubUnits { get; set; }

    public Unit()
    {
        SubUnits = new HashSet<Unit>();
    }
}

和一个带有动作的 API 控制器

public async Task<ActionResult<IEnumerable<Unit>>> GetUnits()
{
    return await _context.Units.ToListAsync();
}

Postman 出现此错误(我不使用 newtonsoft json.net):

<块引用>

System.Text.Json.JsonException:检测到可能的对象循环。这可能是由于循环或对象的深度大于最大允许深度 32。请考虑在 JsonSerializerOptions 上使用 ReferenceHandler.Preserve 以支持循环。

请帮我修复我的代码。谢谢

1 个答案:

答案 0 :(得分:0)

当从上下文直接返回 DBSet 列表而不选择某些成员时,默认的 JSON 序列化程序将序列化具有所有嵌套级别的 DBSet 对象,这将生成您面临的异常以解决此问题,您可以将此代码添加到 Startup 类 ConfigureServices 方法中忽略。

services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);