SQLDataReader 在使用 .Nest() 或 .Read() 时出现错误

SQLDataReader bugging while using .Nest() or .Read()

我正在通过 SQLDataReader 从 MSSQL 中检索一些信息,但是在调试它时我注意到在某些情况下 reader 清除结果视图并出现错误 "Enumeration yielded no results" 请参阅屏幕截图
Before Running passing Read(),
After passing read()


这是我的代码,错误发生在 getActiveUsers() 方法上。 getDatabases() 工作得很好。 有人可以帮助我吗?干杯

 public partial class automation : System.Web.UI.Page
{
    SqlConnection con;
    static List<ActiveUsers> activeUsers = new List<ActiveUsers>();
    protected void Page_Load(object sender, EventArgs e)
    {
        ASPxGridView1.DataSource = activeUsers.ToList();

    }
    public List<ActiveUsers> getDatabases()
    {

        //passing query
        string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name  FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
        //creating connection
        string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
        con = new System.Data.SqlClient.SqlConnection(sqlconn);
        var cmd = new SqlCommand(SqlQuery, con);
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
         List<ActiveUsers> results = new List<ActiveUsers>();
        if (reader.Read())
        {
            while (reader.Read())
            {
                ActiveUsers company = new ActiveUsers();
                company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
                company.ClientName = String.Format("{0}", reader["Name"]);
                results.Add(company);
            }
        }
        con.Close();
        return results;
    }

    public void getActiveUsers()
    {

        activeUsers.Clear();
        List<ActiveUsers> Databases= getDatabases();
        SqlConnection conn = new SqlConnection();
        string SqlQuery = "select [disabled], [ADMN_Users1].[Record_Id] ,[ADMN_Users].[User_Id] from admn_Users1  inner join [ADMN_Users] on [ADMN_Users1].[record_Id] = [ADMN_Users].[Record_Id] Where [disabled] & 0x2 = 0 ";

        for (int i = 0;i < Databases.Count;i++)
        {

            conn.ConnectionString =
            "Data Source=MAXSQLCLUS01;" +
            "Initial Catalog=" + Databases[i].ToString()+";"+
            "User id=sa;" +
            "Password=Max1m1zer;";
            var cmd = new SqlCommand(SqlQuery, conn);
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            int NumberOfUsersCounter = 0 ;
            //TODO Select Enabled users
            if (reader.Read())
            {

                while (reader.Read())
                {
                    string user = String.Format("{0}", reader["User_Id"]);
                    //logic to remove system users

                    if (user.Equals("master", StringComparison.CurrentCultureIgnoreCase))
                    {


                    }
                    else
                    if (user.Equals("emailuser", StringComparison.CurrentCultureIgnoreCase))
                    {

                    }
                    else
                    if (user.Equals("webuser", StringComparison.CurrentCultureIgnoreCase))
                    {


                    }
                    else
                    {

                        NumberOfUsersCounter++;
                    }

                }
                ActiveUsers newEntry = new ActiveUsers();

                newEntry.NumberActiveUsers = NumberOfUsersCounter.ToString();
                newEntry.DatabaseName = Databases[i].DatabaseName.ToString();
                newEntry.ClientName = Databases[i].ClientName.ToString();
                activeUsers.Add(newEntry);

            }
            conn.Close();

            //Add to ActiveUsers list


        }



        ASPxGridView1.AutoGenerateColumns = true;

        ASPxGridView1.DataSource = activeUsers.ToList();
        ASPxGridView1.DataBind();

    }

    protected void ASPxButton1_Click(object sender, EventArgs e)
    {

        getActiveUsers();
    }

    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        ASPxGridView1.DataBind();
        ASPxGridViewExporter1.Landscape = true;
        ASPxGridViewExporter1.FileName = "User Count Report";
        ASPxGridViewExporter1.WriteXlsToResponse();

    }
}

}

if (reader.Read())
{
    while (reader.Read())
    {
       ActiveUsers company = new ActiveUsers();
       company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
       company.ClientName = String.Format("{0}", reader["Name"]);
       results.Add(company);
    }
}

使用这个

if (reader.HasRows)
{
    while (reader.Read())
    {
       ActiveUsers company = new ActiveUsers();
       company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
       company.ClientName = String.Format("{0}", reader["Name"]);
       results.Add(company);
    }
}

你的if条件错误

if(reader.Read()) ==> is Wrong 

Read() 不是 return 布尔值

使用 HasRows 检查 SQLDataReader 中的行

您正在跳过第一个结果。 if (reader.Read()) { while(reader.Read()) {.... 删除封闭的 if,它所做的只是查看是否有一行并检索它,但随后您不读取它,而是在 if 中再次读取,因此第一个结果总是被丢弃。

public List<ActiveUsers> getDatabases()
{
    //passing query
    string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name  FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
    //creating connection
    string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;

    using(con = new System.Data.SqlClient.SqlConnection(sqlconn))
    using(var cmd = new SqlCommand(SqlQuery, con))
    {
        con.Open();
        using(SqlDataReader reader = cmd.ExecuteReader())
        {
            List<ActiveUsers> results = new List<ActiveUsers>();
            while (reader.Read())
            {
                ActiveUsers company = new ActiveUsers();
                company.DatabaseName = reader.GetString(0);
                company.ClientName = reader.GetString(1);
                results.Add(company);
            }
        }
    }
    return results;
}

旁注:

  • company.DatabaseName = String.Format("{0}", reader["WorkspaceName"])最好写成company.DatabaseName = reader.GetString(0)。下一行也是如此。无需使用 string.Format 并且您要在查询中指定列和顺序,因此请使用序号索引以获取本机值。
  • 我建议您将 SqlConnectionSqlDataReader 包裹在 using 块中,以确保它们在使用后 closed/disposed 即使在出现异常的情况下也是如此。