SQL查询结果错误:查询运算符' ElementAt'不受支持

时间:2016-07-07 16:26:21

标签: c# .net sql-server database visual-studio

我试图用 do-while 循环遍历SQL Query结果,但是结果变量的索引存在问题。

问题在于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

1 个答案:

答案 0 :(得分:3)

首先请注意,每次枚举IQueryable(这是linq表达式的结果类型)时,您再次访问数据库。相反,通过执行

来获取查询的本地缓存
var result = selectQuery.ToArray();

或类似的东西。

执行此操作后,result.ElementAt应该可以正常工作,而您只能访问数据库一次。

示例:

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

由于您尝试在ElementAt上使用IQueryable,实体框架正试图将其转换为SQL命令,它不知道该怎么做,因此错误

相关问题