2016-07-07 70 views
0

我試圖循環SQL查詢結果do-while循環,但是存在結果變量索引問題。SQL查詢結果錯誤:查詢運算符'ElementAt'不受支持

的問題是與while (selectQuery.ElementAt(i).Source != user.Item1 && selectQuery.ElementAt(i).UserID != user.Item2 && i<selectQuery.Count());

所以我的問題是該行:我怎能指數的SQL查詢結果的變量?

這裏是我的代碼:

 //------------------Database connection initialization-------------------------- 
     string m_dbConnestionString = "Server=aaa; Database=bbb; uid=ccc; pwd=ddd; Trusted_Connection=True;" 
     DataClasses1DataContext db = new DataClasses1DataContext(m_dbConnectionString); 
     Table<Central> m_myTable = db.GetTable<Central>() 
     // -----------------------------------------------------------------------------    

     int i = -1; 

     var selectQuery = 
      from central in m_myTable 
      select central; 


     foreach (var row in selectQuery) 
     { 
      Console.WriteLine("{0}; {1}",row.DisplayName, row.Email); 
     } 


     foreach (var user in allMailusers) // btw, allMailUsers is List<Tuple<string, string, string, string, string>> 
     { 

      do 
      { 

       i += 1; 

      } while (selectQuery.ElementAt(i).Source != user.Item1 && selectQuery.ElementAt(i).UserID != user.Item2 && i<selectQuery.Count()); 

      if (selectQuery.ElementAt(i).Source != user.Item1 && selectQuery.ElementAt(i).UserID != user.Item2) // if true, insert into DB 
      { 
       // create new instance of Central 
       Central c1 = new test1.Central(); 

       // fill up c1 with values 
       c1.UserID  = selectQuery.ElementAt(i).UserID; 
       c1.Source  = selectQuery.ElementAt(i).Source; 
       c1.DisplayName = selectQuery.ElementAt(i).DisplayName; 
       c1.Email  = selectQuery.ElementAt(i).Email; 
       c1.Phone  = selectQuery.ElementAt(i).Phone; 

       // insert into db 
       m_myDb.Centrals.InsertOnSubmit(c1); 
       m_myDb.SubmitChanges(); 

      } // end if 

      i = -1; 
     } // end of foreach 

回答

3

首先,請注意,每次枚舉的IQueryable時間(這是你LINQ表達式的結果類型),你再次命中數據庫。相反,通過做一個本地緩存查詢您的查詢

var result = selectQuery.ToArray(); 

或類似的東西。

一旦你這樣做,result.ElementAt應該可以工作,而且你只需要打一次數據庫。

例子:

foreach (var row in result) 
{ 
    Console.WriteLine("{0}; {1}",row.DisplayName, row.Email); 
} 

既然你想上的IQueryable使用ElementAt,實體框架試圖翻譯成一個SQL命令時,它不知道該怎麼辦,因此錯誤。