C # При выполнении запроса dataTable не загружается, и я получаю исключение истечения срока действия - PullRequest
0 голосов
/ 09 ноября 2018

как дела?

У меня проблема с загрузкой данных из БД (строка подключения хорошая, так как я могу вставить данные в БД) в мою таблицу данных.

мой запрос также работает нормально, когда я выполняю его в Sql management studio, я получил 15 записей ... поэтому после некоторого одиночного поиска и попыток я пришел к вам.

Вот код моей функции, которая должна получить значение из БД.

Код останавливается на «dt.Load (sqlCommand.ExecuteReader ());» где, кажется, поиск, но я получаю через несколько секунд, исключение тайм-аут А я как я

 public List<string> GetConfigurationValues(string configurationKey, int? idBusinessUnit, int? idDomain)
        {
            string conn = ConnectionStringHelper.GetIdentityConnectionString();


            List<string> conf = new List<string>();
            using (SqlConnection dbConnection = new SqlConnection(conn))
            {
                dbConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(@"
                        SELECT Value 
                        FROM ConfigurationValue cv
                        INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
                        INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
                        WHERE ck.KeyName = @ConfigurationKey
                        AND((cf.idDomain = @idDomain) OR(cf.idDomain IS NULL))
                        AND((cf.idBusinessUnit = @idBusinessUnit) OR(cf.idBusinessUnit IS NULL))", dbConnection);
                sqlCommand.CommandType = System.Data.CommandType.Text;

                sqlCommand.Parameters.Add(new SqlParameter("@ConfigurationKey", "PORTAL_THEME"));

                if (idBusinessUnit == null)
                    sqlCommand.Parameters.Add(new SqlParameter("@idBusinessUnit", null)); //DBNull.Value
                else
                    sqlCommand.Parameters.Add(new SqlParameter("@idBusinessUnit", null));

                if (idDomain == null)
                    sqlCommand.Parameters.Add(new SqlParameter("@idDomain", null));// DBNull.Value
                else
                    sqlCommand.Parameters.Add(new SqlParameter("@idDomain", 281));


                DataTable dt = new DataTable();        
                dt.Load(sqlCommand.ExecuteReader());
                //dbConnection.Close();

                if (dt != null)
                    if (dt.Rows.Count > 0)
                        foreach (DataRow dr in dt.Rows)
                            conf.Add(Convert.ToString(dr["Value"]));
            }
            return conf;
        }

Ответы [ 2 ]

0 голосов
/ 09 ноября 2018

спасибо, за ваше внимание. Я решил это сегодня утром. это была проблема в том, как я исключил загрузку dataTable. Вместо dataTable я использую сейчас DataReader. Я уточняю, что если мы используем dataReader, мы получим правильное сообщение об ошибке (это бонус.) Итак, вот часть кода, которую я изменил (для тех, кто хочет знать):

 public List<string> GetConfigurationValues(string configurationKey, int? idBusinessUnit, int? idDomain)
    {
        string conn = ConnectionStringHelper.GetIdentityConnectionString();
        string valueRes;

        int idConfigurationKey = 0;

        if (configurationKey == "PORTAL_THEME") { idConfigurationKey = 3; }
        else if (configurationKey == "LOGO_THEME") { idConfigurationKey = 4; }

        List<string> conf = new List<string>();
        DataTable dt = new DataTable();
        using (SqlConnection dbConnection = new SqlConnection(conn))
        {
            dbConnection.Open();
            SqlCommand command = dbConnection.CreateCommand();
            SqlTransaction transaction;
            transaction = dbConnection.BeginTransaction("SampleTransaction");

            command.Connection = dbConnection;
            command.Transaction = transaction;

            try
            {

                command.CommandText = @"
                    SELECT Value 
                    FROM ConfigurationValue cv
                    INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
                    INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
                    WHERE cf.idConfigurationKey = @ConfigurationKey
                    AND((cf.idDomain = @idDomain) OR(cf.idDomain IS NULL))
                    AND((cf.idBusinessUnit = @idBusinessUnit) OR(cf.idBusinessUnit IS NULL))";
                command.CommandType = System.Data.CommandType.Text;

                command.Parameters.Add(new SqlParameter("@ConfigurationKey", idConfigurationKey));

            if (idBusinessUnit == null)
                    command.Parameters.Add(new SqlParameter("@idBusinessUnit", DBNull.Value)); //DBNull.Value
            else
                    command.Parameters.Add(new SqlParameter("@idBusinessUnit", idBusinessUnit));

            if (idDomain == null)
                    command.Parameters.Add(new SqlParameter("@idDomain", null));// DBNull.Value
            else
                    command.Parameters.Add(new SqlParameter("@idDomain", idDomain));


                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string theme = reader["Value"].ToString();
                        conf.Add(theme);
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
                reader.Close();

            }
            catch (Exception ex)
            {
                Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
                Console.WriteLine("  Message: {0}", ex.Message);

            }

        }
        return conf;
    }
0 голосов
/ 09 ноября 2018

Попробуйте это:

SqlCommand sqlCommand = new SqlCommand(@"
                        SELECT Value 
                        FROM ConfigurationValue cv
                        INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue
                        INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey
                        WHERE ck.KeyName = @ConfigurationKey
                        AND((cf.idDomain = @idDomain) OR(cf.idDomain IS NULL))
                        AND((cf.idBusinessUnit = @idBusinessUnit) OR(cf.idBusinessUnit IS NULL))", dbConnection);

sqlCommand .CommandTimeout = 500;
...