SQL 查询结果错误:不支持查询运算符“ElementAt”

本文关键字:查询 ElementAt 运算符 结果 错误 SQL 不支持 | 更新日期: 2023-09-27 17:55:39

我正在尝试使用 do-while 循环遍历 SQL 查询结果,但结果变量的索引存在问题。

问题与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

SQL 查询结果错误:不支持查询运算符“ElementAt”

首先,请注意,每次枚举IQueryable(这是 linq 表达式的结果类型)时,都会再次访问数据库。 相反,请通过执行以下命令获取查询的本地缓存

var result = selectQuery.ToArray();

或类似的东西。

一旦你这样做,result.ElementAt应该工作,你只访问数据库一次。

例:

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

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