I'm developing a test application using ASP.Net MVC 5, Entity Framework with SQL Server.
In my scenario there are 2 tables in the database. Student
and Qualification
.
one Student has one or more qualifications.
I need to get a student
from the database by giving studentID and the Qualification
list of the Student
(Navigation property) should contain all the qualifications he or she has.
The controller method which I have implemented as follows.
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);
}
But when I am trying to call this function, it shows this error.
A circular reference was detected while serializing an object of type 'App1.Models.Student'.
How to fix this issue.
I need to pass full list of qualification with the Student
instance.
My Student Model class as follows
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; }
}
My Qualification
Model class as follows
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; }
}
Above Model class has been generated by using Entity Data Model. I follow Database First Approach..
Thanks in advance.