假设我有两个表,一个是学生表,一个是学校表。在我的学生表中,我有一个外键fkSchoolId链接到一个学校记录。然而,如果我按照以下方式检索我的记录:
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();
}
}
我将拥有学生对象列表,并且可以在foreach循环中访问它。但是当我按照下面的方法操作时,当检索学校名称时会出现错误。
foreach(Student student in DAL.StudentLogic.GetByType(5))
{
string schoolName = student.School.Name;
}
System.ObjectDisposedException:“无法访问已处理的对象。对象名称:“DataContext accessed after Dispose.”。
请问我该如何获取存储在返回对象中的外部信息,以便我可以访问它们?或者更好的方法是,如果我可以指定仅加载学校名称呢?
更新: 如果我按照以下方式进行操作,它可以正常工作,但不确定它会对性能产生多大影响。我将进行基准测试,并在下周再次更新此主题。
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;
}
}
}
我将能够在我的返回对象中访问student.School.Name。