Let say I have 2 tables which is Student and School. Within my Student table I have a fkSchoolId linking to a School record. However, if I retrieve my record as below
public static List<Student> GetByType(string connString, int type)
{
using (mydb_DataContext db = new mydb_dbDataContext(connString))
{
return (from t1 in db.Students
where t1.type = type
select t1).ToList();
}
}
I will have the list of Student objects where I can access it in a foreach loop. But when I do as below, I will get an error when retrieving the school name.
foreach(Student student in DAL.StudentLogic.GetByType(5))
{
string schoolName = student.School.Name;
}
System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.'
May I know how can I get the foreign information stored in the return object so that I can access them? Or better way, if I can specify to load up just the school Name?
Updated: If I do as follow, it works, but not sure how much it will impact the performance. I will do a benchmark and update to this topic again next week.
public static List<Student> GetByType(string connString, int type)
{
using (mydb_DataContext db = new mydb_dbDataContext(connString))
{
List<Student> students = (from t1 in db.Students where t1.type = type select t1).ToList();
foreach(Student student in students)
{
student.School.Name = db.Schools.Where(q => q.SchoolId == student.fkSchoolId).FirstOrDefault().Name;
}
}
}
I'll be able to access to student.School.Name in my return object.