2013-04-10 33 views
1

任何提示如何關閉DataReader?我使用postgresql,MARS僅適用於SQL。或者也許我不需要MARS來解決這個問題,我不知道。該錯誤顯示在foreach循環中。感謝您的提示。另一個「已經有一個開放的DataReader關聯......」

var months = (from month in connector.PositionInstance where month.FeeNoticeMonth >= DateTime.Now.Month select month); 

foreach (PositionInstance p in months) 
{ 
    System.Windows.MessageBox.Show("" + p.First().Position.Name); 
} 

編輯: 我有兩個表PositionInstance和位置:

CREATE TABLE "Position" 
(
"PositionId" integer NOT NULL DEFAULT, 
"Name" character varying(30) NOT NULL, 
CONSTRAINT "PK_Position" PRIMARY KEY ("PositionId") 
) 

CREATE TABLE "PositionInstance" 
(
"PositionInstanceId" integer NOT NULL DEFAULT, 
"FeeNoticeYear" integer NOT NULL, 
"FeeNoticeMonth" integer NOT NULL, 
CONSTRAINT "PK_PositionInstance" PRIMARY KEY ("PositionInstanceId"), 
CONSTRAINT "FK_Position_PositionInstance" FOREIGN KEY ("PositionId") 
REFERENCES "Position" ("PositionId") MATCH SIMPLE 
ON UPDATE NO ACTION ON DELETE NO ACTION 
) 
+2

看不到整個代碼,但你嘗試添加一個ToList()到你的linq語句嗎? – JMan 2013-04-10 13:06:00

回答

1

嘗試在連接字符串中添加此:

MultipleActiveResultSets =真

+1

我使用postgresql。我認爲MARS只適用於SQL – Georg 2013-04-10 13:08:43

2

這個問題可能發生在你的情況下,由於延遲加載,發生在foreach循環內部。它試圖在循環的每次迭代中從DB加載每個Position

解決此問題的一種方法是使用預先加載在查詢中立即獲取所有Positions。然後,如果您在查詢結束時還使用貪婪操作(例如ToList()),則會執行該數據庫,並且一切都會一拉一拉。在你的情況下嘗試類似

var months = 
    (from month in connector.PositionInstance 
    where month.FeeNoticeMonth >= DateTime.Now.Month 
    select month).Include("Position").ToList(); 

或一些變化。在查詢後使用ToList()鍵入變量months作爲List(這是一個IEnumerable),其中包含來自DB的填充結果;否則months將是一個IQueryable與數據庫查詢尚未執行。

相關問題