简体   繁体   English

实体框架自引用类

[英]Entity Framework self referencing class

["

I have a class like this<\/i>我有这样的课<\/b><\/p>

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

when return list of DBSet from context direct without select certain members the default JSON serializer will work to serialize DBSet object with all nested levels this will generate the exception you face to solve this you can add this code to the Startup class ConfigureServices method to ignore .当从上下文直接返回 DBSet 列表而不选择某些成员时,默认 JSON 序列化程序将用于序列化具有所有嵌套级别的 DBSet 对象,这将生成您面临的异常来解决此问题,您可以将此代码添加到 Startup 类 ConfigureServices 方法中以忽略。

services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions
        .ReferenceHandler = ReferenceHandler.IgnoreCycles);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM