首页 > 解决方案 > 如何在部署环境中摆脱“与此命令关联的 DataReader”

问题描述

我尝试在这里搜索与此问题相关的答案,所有这些答案都可以在测试环境中工作,但不能在部署中使用。

我有这个功能在测试环境中运行良好:

    static SqlConnection dbconn = new SqlConnection("Data Source=192.168.0.73;Initial Catalog=CAMFIN;Integrated Security=False;User ID=user;Password=password;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");


    private static void CreateTable(string query, string filename, string subject, string reportref, string branch)
    {
        Console.WriteLine("Preparing data....");
        if (dbconn.State == ConnectionState.Closed)
        {
            dbconn.Open();
        }

        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();

        using (SqlCommand cmd = new SqlCommand(query, dbconn))
        {
            cmd.Parameters.AddWithValue("@date", DateTime.Today);
            cmd.Parameters.AddWithValue("@branch", branch);

            cmd.CommandType = CommandType.Text;
            cmd.CommandTimeout = 0;

            da.SelectCommand = cmd;
            da.Fill(dt); //throws an error on production


            if (dt.Rows.Count >= 1)
            {
                string attachments = filedir + filename + ".xlsx";
                DatatableToExcel(dt, attachments, subject, filename);
                filestosend.Add(attachments);
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(branchname + " Office has no data to bound.");
            }
        }
    }

当我在生产中对其进行测试时,该函数会抛出错误。

Error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: There is already an open DataReader associated with this Command which must be closed first.

标签: c#datatablesqldataadapter

解决方案


推荐阅读