我使用以下代码获得了Student
表的主键:
var stud_id = (from p in context.Students
where p.Student_Name == "Bruce"
select p.Student_Id );
当我尝试使用stud_id
检索整个实体时,使用以下代码:
Student requiredstud = new Student();
foreach (var p in stud_id)
{
//Console.WriteLine(p);
requiredObj = context.Students.Find(p);
string tempObj = JsonSerializer.SerializeToString<Student>(requiredObj);
Console.WriteLine(tempObj);
}
它在该行上给出了以下异常:
requiredObj = context.Students.Find(p);
如何解决此问题并获取student
修改 的InnerException
是:{"There is already an open DataReader associated with this Command which must be closed first."}
答案 0 :(得分:0)
由于您正在迭代IQueryable
并尝试使用相同的context
找到另一位学生,因此您将获得异常。您应该在查询中执行.ToList
迭代它并从数据库中获取记录。稍后您可以在foreach循环中使用上下文。所以你的查询可以是:
var stud_id = (from p in context.Students
where p.Student_Name == "Bruce"
select p.Student_Id ).ToList();
或者
var stud_id = context.Students.Where(p=> p.Student_Name == "Bruce").ToList();