【发布时间】:2017-09-09 11:15:23
【问题描述】:
假设我有 2 张桌子,即学生和学校。在我的学生表中,我有一个链接到学校记录的 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();
}
}
我将拥有 Student 对象的列表,我可以在 foreach 循环中访问它。但是当我按如下操作时,检索学校名称时会出错。
foreach(Student student in DAL.StudentLogic.GetByType(5))
{
string schoolName = student.School.Name;
}
System.ObjectDisposedException: '无法访问已处置的对象。 对象名称:'在 Dispose 之后访问的 DataContext。'。'
我可以知道如何获取存储在返回对象中的外国信息以便我可以访问它们吗?或者更好的方法,如果我可以指定只加载学校名称?
更新: 如果我按照以下操作,它可以工作,但不确定它会对性能产生多大影响。我将在下周再次进行基准测试并更新此主题。
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。
【问题讨论】:
-
此解决方案将为每个返回的学生执行单独的查询。很遗憾去DB这么多次..
-
@GiladGreen 我同意.. 不是最好的性能.. 我想知道为什么 LINQ to SQL 没有一个简单的方法来统计我想带回来.. 我试过 DeferredLoadingEnabled 但我仍然得到空的异物。我不想步入 C#7。如果我使用实体框架,那里有一个 .Include,它会与 EF 一起解决我的问题吗?
-
但是包含在 LINQ to SQL 中不可用,对吧?
标签: c# linq linq-to-sql