2012-12-31 86 views
0

我有使用下面的代碼Student表的主鍵:無法檢索上下文中的foreach循環跟蹤實體

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."}

+0

點擊'查看詳情...',看到了內部異常,你可以把它添加到你的問題 – Habib

+0

@Habib:新增的InnerException爲 –

回答

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(); 
+0

var stud_id = context.Students.Where(p.Student_Name ==「Bruce」)。ToList(); ,它給出的錯誤是p在當前上下文中不是exixst。 –

+0

@BhushanFrake,ohh,錯過了一件簡單的事情。檢查編輯它應該是'var stud_id = context.Students.Where(p => p.Student_Name ==「Bruce」)。ToList();' – Habib

+0

:指定的參數類型'University.Student'無效。只支持標量類型,如System.Int32,System.Decimal,System.DateTime和System.Guid。 –