我正在開發一個測試應用程序使用ASP.Net MVC 5,實體框架與SQL Server。序列化對象時檢測到循環引用+ ASP.net mvc5 +實體框架
在我的方案中,數據庫中有2個表。 Student
和Qualification
。 一個學生有一個或多個資格。
我需要給studentID和Student
(導航性能)的Qualification
列表,從數據庫中獲取一個student
應該包含所有他或她有資格。
我實施的控制器方法如下。
public JsonResult getStudentInfo(int studentId)
{
db.Configuration.ProxyCreationEnabled = false;
Student ss = (Student) (from s in db.Students where s.Id == studentId select s).FirstOrDefault();
ss.Qualifications = (from q in db.Qualifications where q.StudentId == ss.Id select q).ToList();
return Json(ss, JsonRequestBehavior.AllowGet);
}
但是當我試圖調用這個函數時,它顯示這個錯誤。
A circular reference was detected while serializing an object of type 'App1.Models.Student'.
如何來解決這個問題。 我需要通過Student
實例的資格完整列表。
我的學生模型類,如下所示
public partial class Student
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Student()
{
this.Qualifications = new HashSet<Qualification>();
}
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> Age { get; set; }
public Nullable<byte> Gender { get; set; }
public string City { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Qualification> Qualifications { get; set; }
}
我Qualification
Model類如下
public partial class Qualification
{
public int Id { get; set; }
public Nullable<int> StudentId { get; set; }
public string QualificationName { get; set; }
public string Institute { get; set; }
public Nullable<System.DateTime> EffectiveDate { get; set; }
public virtual Student Student { get; set; }
}
上述模型類已通過實體數據模型生成的。 我遵循數據庫第一方法..
在此先感謝。
Qualification類是什麼樣的? – Robert
@羅伯特對不起。我剛更新了這個問題。 – JayNaz
是的......我猜羅伯特猜對了;學生 - > qualification->的學生。是你的循環參考。在過去,我編寫代碼將Student.Qualification.Student設置爲null,這樣就不會發生這種情況。我相信有更好的解決方案。我不知道它是否可以解決這個問題,但你可以試試這個庫:https://github.com/zzzprojects/GraphDiff – theGleep