【问题标题】:Entity Framework self referencing class实体框架自引用类
【发布时间】:2021-09-25 09:46:41
【问题描述】:

我有这样的课

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 以支持循环。

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

【问题讨论】:

标签: c# json api entity-framework


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    相关资源
    最近更新 更多