我有臭名昭着的“未能启用约束”例外,但this question的答案都不适用,因为我没有使用DataSet
或TableAdatper
:
DataTable tblTypes = connVeekun.ExecuteDataTable("SELECT id, damage_class_id, " +
"(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 1) AS name_ja, " +
"(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 9) AS name_en, " +
"(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 5) AS name_fr, " +
"(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 8) AS name_it, " +
"(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 6) AS name_de, " +
"(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 7) AS name_es, " +
"(SELECT name FROM type_names WHERE type_names.type_id = types.id AND local_language_id = 3) AS name_ko " +
"FROM types ORDER BY id");
帮助方法:
/// <summary>
/// Runs a command and returns a DataTable containing its results.
/// </summary>
/// <param name="db">Open data connection</param>
/// <param name="sqlstr">SQL string</param>
/// <param name="_params">List of parameters to use with the SQL</param>
public static DataTable ExecuteDataTable(this DbConnection conn, String sqlstr, params IDataParameter[] _params)
{
DbCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlstr;
cmd.Parameters.AddRange(_params);
DbDataReader reader = cmd.ExecuteReader();
DataTable result = new DataTable();
result.Load(reader);
return result;
}
失败的约束是name_ko
列中存在空值。由于我没有使用DataAdapter
,我无法更改(推断)架构或禁用约束。在我的应用程序中,保留name_ko
列的空值非常重要,因此修改SQL以删除空值不是一种选择。
数据来自Eevee's Pokédex。
答案 0 :(得分:0)
来自docs:
该方法还从结果集中检索约束信息 对于所有添加的列。除主键约束的情况外, 此约束信息仅在当前DataTable使用时使用 在加载操作开始时不包含任何列。
看起来如果您为表设置架构(通过创建所有列)然后加载它,您将解决约束问题,因为他的方法不会推断约束。