c# - 列 'country_id' 不属于 table 。- 错误类型:System.Data.DataColumn GetDataColumn(System.String)
问题描述
仅在服务器错误日志上随机获取此错误,实际上 GetAllCountries 程序总是返回所有国家,没有 country_id 就没有结果的机会
我将响应数据表记录到一个文件中,有趣的是,记录的响应是由另一个从其他函数调用的存储过程返回的。我认为 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
解决方案
你的问题可能在这里吗?
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"])
.
推荐阅读
- wordpress - 如何阻止 WordPress 自动进行重定向?
- javascript - 从任何给定元素中提取 CSS 规则
- c# - 泛型类型参数的 IEnumerable
? - java - 以其他语言读取的 ObjectOutputStream
- php - 带有 PHP SDK 的 Facebook JavaScript 助手突然停止工作
- javascript - 使用 Google 反向地理编码的 400 错误请求
- visual-studio-code - 在 WSL 中运行 vscode 会引发 v8 二进制文件和快照之间的致命错误版本不匹配
- graphql - Keystone.JS API 用户认证(不是 Admin-UI)
- android - 如何将 Workmanager 任务完成通知服务?
- sql - 将表达式转换为数据类型日期时间的算术溢出错误