【问题标题】:SQL Query result error: The query operator 'ElementAt' is not supportedSQL 查询结果错误:不支持查询运算符“ElementAt”
【发布时间】:2016-07-07 16:26:20
【问题描述】:

我正在尝试使用 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

【问题讨论】:

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


    【解决方案1】:

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

    var result = selectQuery.ToArray();
    

    或类似的东西。

    一旦你这样做了,result.ElementAt 应该可以工作,而且你只会访问数据库一次。

    例子:

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

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

    【讨论】:

      猜你喜欢
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      相关资源
      最近更新 更多