无法在foreach循环中检索由上下文跟踪的实体

时间:2012-12-31 04:34:02

标签: c# entity-framework-4

我使用以下代码获得了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);

enter image description here

如何解决此问题并获取student

的详细信息

修改     的InnerException

是:{"There is already an open DataReader associated with this Command which must be closed first."}

1 个答案:

答案 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();