I am having an issue with my database model. I am fairly new to this, thus sorry in advance. Here are how my auto generated classes look like...

Session Model

public partial class Session
{
    public Session()
    {
        this.Tutors = new HashSet<Tutor>();
    }

    public int SessionId { get; set; }
    public int StudentStudentId { get; set; }

    public virtual Student Student { get; set; }
    public virtual ICollection<Tutor> Tutors { get; set; }
}

Student Model

public partial class Student
{
    public Student()
    {
        this.Sessions = new HashSet<Session>();
    }

    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Session> Sessions { get; set; }
}

Controller

    public Student Get(int id)
    {

        using(var db = new studytree_dbEntities())
        {

            Student s = db.Students.FirstOrDefault(i => i.StudentId == id);



         return s;
        }
    }

I know what the problem is. The database queries from the student table receiving the data. Since it has a sessionid column, it goes to the session table and queries the session. But since it is a one to many relationship, the session table has one student, thus a loop is created. A student grabs it session and the session grabs its student etc.... How can I make it so that it only goes one level deep. What I want to be able to do is query a student and get all its properties.

有帮助吗?

解决方案

One approach is to manually materialize the student and her sessions, without materializing the session's student reference. This code assumes that Tutor does not reference any students. If it does you'll need to manually materialize Tutor as well.

using(var db = new studytree_dbEntities())
{

    Student s = db.Students
        .Where(s => s.StudentId == id)
        .ToList()
        .Select(s => new Student {
            FirstName = s.FirstName,
            LastName = s.LastName,
            Sessions = s.Sessions.Select(session => new Session {
                Tutors = session.Tutors
            }),
        })
        .FirstOrDefault();
    return s;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top