Столбец 'country_id' не принадлежит таблице. - Тип ошибки: System.Data.DataColumn GetDataColumn (System.String) - PullRequest
0 голосов
/ 01 ноября 2019

Получение этой ошибки случайным образом только в журнале ошибок сервера, фактически процедура GetAllCountries всегда возвращает все страны, и нет никакого шанса на результат без country_id

. Я записал ответ DataTable в файл, и интересный этотявляется то, что зарегистрированный ответ был возвращен другой хранимой процедурой, вызванной из другой функции. Я думаю, что класс DBHelper разделил оба ответа или sql выполняет неправильную процедуру.

public List<Country> GetAllCountry()
    {
        List<Country> countries = new List<Country>();

        try
        {
            SqlCommand cmd = new SqlCommand();
            DataTable dt = new DataTable();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "GetAllCountries";
            dt = DBHelper.Read(cmd);

            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Country country = new Country();
                    country.CountryId = Convert.ToInt32(dr["country_id"]);
                    country.CountryCode =Convert.ToString(dr["country_code"]);
                    country.CountryName =Convert.ToString(dr["country_name"]);

                    countries.Add(country);
                }
            }
        }
        catch(Exception ex)
        {
            SysError.LogError(ex, "", "country", "GetAllCountry");
        }

        return countries;
    }

Read Function

public static class DBHelper
{

     private static string ConnStr;
                private static string Connection= "SettingsDB";
         public static DataTable Read(SqlCommand cmd)
                {

                    ConnStr = 
          ConfigurationManager.ConnectionStrings[Connection].ConnectionString;
                    DataTable dt = new DataTable();
                    using (SqlConnection con = new SqlConnection(ConnStr))
                        try
                        {

                            using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
                            {
                                cmd.Connection = con;
                                con.Open();
                                dt.Locale = 
            System.Globalization.CultureInfo.InvariantCulture;
                                adp.Fill(dt);
                            }
                        }
                        catch (Exception ex)
                        {
                             SysError.LogError(ex, "Read", "", "");
                        }
                        finally
                        {
                            con.Close();
                        }

                    return dt;
                }
}

Хранимая процедура в вопросе:

select country_id ,
country_code ,
country_name +' '+'('+country_code+')' as country_name
from tbl_country 
order by country_name asc

1 Ответ

0 голосов
/ 01 ноября 2019

Возможно ли, что ваша проблема здесь?

                    Country country = new Country();
                    Country.CountryId = Convert.ToInt32(dr["country_id"]);
                    Country.CountryCode =Convert.ToString(dr["country_code"]);
                    Country.CountryName =Convert.ToString(dr["country_name"]);

                    countries.Add(country);

Вы создаете новый экземпляр класса Country с именем страны (нижний регистр);однако все назначения (надлежащий регистр) предназначены для точки имени класса (Country.), а не для экземпляра имени. Затем вы добавляете экземпляр класса в список. Также я согласен с @mortb по поводу (dr["country_name"]).

...