.net EF核心-循环实体json
我的实体:.net EF核心-循环实体json,.net,json,entity-framework,core,.net,Json,Entity Framework,Core,我的实体: { public Student() { Grades = new HashSet<Grade>(); } [Key] public int StudentId { get; set; } [ForeignKey("Users")] public string UserId { get; set; } pub
{
public Student()
{
Grades = new HashSet<Grade>();
}
[Key]
public int StudentId { get; set; }
[ForeignKey("Users")]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
[ForeignKey("Parent")]
public int? ParentId { get; set; }
public Parent Parent { get; set; }
public int? SectionId { get; set; }
public string FatherName { get; set; }
public int classNumber { get; set; }
public Section Section { get; set; }
public string brevetResult { get; set; }
public DateTime? dateLeftAec { get; set; }
public string additionalInfo { get; set; }
public bool bacc { get; set; }
public string baccResult { get; set; }
public string baccSection { get; set; }
public int BrandId { get; set; }
[JsonIgnore]
public Brand Brand { get; set; }
public virtual ICollection<StudentRegistration> StudentReg { get; set; }
public virtual ICollection<Grade> Grades { get; set; }
public virtual ICollection<Absence> Absences { get; set; }
public virtual ICollection<StudentStudyYear> StudentStudyYears { get; set; }
}
public class Grade: IBrand
{
public int gradeId { get; set; }
public int grade { get; set; }
public int StudentId { get; set; }
public int SubjectId { get; set; }
public int TeacherId { get; set; }
public int TermId { get; set; }
public int SectionId { get; set; }
public bool IsApproved { get; set; }
public string ResultToEdit { get; set; }
public bool IsEditedByAdmin { get; set; }
public virtual Student Student { get; set; }
public virtual Subject Subject { get; set; }
public virtual Teacher Teacher { get; set; }
public virtual Term Term { get; set; }
public virtual Section Section { get; set; }
public int BrandId { get; set; }
[JsonIgnore]
public Brand Brand { get; set; }
public virtual ICollection<GradeStudyYear> GradeStudyYears { get; set; }
}
问题解决了,但现在我得到的数据大小为5gb,所以它仍然是循环的,没有错误
我试图将属性[JSONIgnore]放入grade.cs文件中,但过了一段时间,我需要从grade中获取student,因此它将不会有用:(解决此错误的方法是什么?请提前感谢,序列化实体会导致许多问题,并会暴露有关您域的更多信息。当将数据返回到视图或API使用者时,您可以定义视图模型或DTO,以仅包含使用者在最适合此功能的任何结构中所需的详细信息需要。这避免了EF导航属性可能导致的引用问题,减少了向客户端公开的领域知识和数据量,并将有效负载大小最小化到所需的程度。数据可以展平,因此,如果要显示一个实体的列表,则不需要为每个相关实体提供ViewModel/DTO,您的视图模型只需仅包含适用于该消费者的任何相关实体的相关详细信息
定义视图模型/DTO后,可以使用
.Select()
填充它,或者使用Automapper设置映射并使用.ProjectTo()填充它
我建议不要序列化您的EF模型,而是使用平面DTO对象。JSON无法继承地处理对象引用,因此您需要自己处理它们(或者让另一个库为您处理)。
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});