简体   繁体   中英

Entity Framework self referencing class

["

I have a class like this<\/i>

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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