星期二, 8月 12, 2008

The query results cannot be enumerated more than once. 錯誤..

今天在用linq去處理store procedure資料時..頁面跳出一個錯誤..

The query results cannot be enumerated more than once.

google一下找了是否也有人跟我遇到相同的問題..原來原因是..是傳回ISingleResult<T>這個問題..Loser..我們先看一段程式碼..

da.linqToSqlDataContext db = new da.linqToSqlDataContext();

//從store procedure抓出來資料
var aaaa = db.StoredProcedure2().Select(a => a);
//把一個欄位的總和抓出來
double sumA = aaaa.Sum(a => Convert.ToDouble(a.a));
//把剛剛處理好的值拿出來跟欄位計算
var testA = aaaa.Select(a => new { test = Convert.ToDouble(a.a) / sumA });
//列出資料
foreach (var a in testA)
{
Response.Write(a + "<br />");
}

這段程式碼..會產生上面那段錯誤..原因就是aaaa被判斷成ISingleResult<T>的型別..而ISingleResult<T>不能被enumerate一次以上..所以就會發生exception..

解決方法就是把ToList()這樣就行了..

var aaaa = db.StoredProcedure2().Select(a => a).ToList();

解決..SleepySleepySleepySleepySleepySleepySleepySleepySleepy...

參考:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2618572&SiteID=1

沒有留言: