【发布时间】:2012-10-10 21:56:57
【问题描述】:
我正在尝试将一组规则“批量”插入到规则表中。该表的结构如下:
RuleId int,
Rule nvarchar(256),
Domain nvarchar(256),
RuleTypeId int,
ExpirationDate DateTime
在我的插入函数中,我尝试在获得表的架构后设置一行的列,但似乎该行不包含指定的列(请注意,我没有指定RuleId,因为它是自动生成的):
private void InsertRulesXml(List<Rule> rules)
{
using (DataSet ds = new DataSet())
{
using (DataTable rulesTable = GetSchemeForTable("RulesTable"))
{
// Add the rules to the table
foreach (Rule rule in rules)
{
DataRow row = rulesTable.NewRow();
// When I try to set the specific column it tells me that the column doesn't exist
row["Rule"] = rule.Rule;
row["Domain"] = rule.Domain;
row["RuleTypeId"] = rule.RuleTypeId;
row["ExpirationDate"] = rule.Expiration;
rulesTable.Rows.Add(row);
}
ds.Tables.Add(rulesTable);
// Convert the data to XML
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
rulesTable.WriteXml(sw, System.Data.XmlWriteMode.WriteSchema);
}
// Insert the XML rules
InsertUpdateRulesXml(sb.ToString());
}
}
}
这里是获取指定表架构的函数:
private DataTable GetSchemeForTable(string tableName)
{
DataTable ret = null;
using (SqlConnection connection = GetContentScraperSqlConnection())
{
try
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = string.Format("SELECT TOP 0 [{0}].* FROM [{0}] WHERE 1 = 2;", tableName);
using (IDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly))
{
ret = reader.GetSchemaTable();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception in GetSchemeForTable: " + ex.ToString());
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
connection.Dispose();
}
}
return ret;
}
问题:当我尝试设置特定列时,它告诉我该列不存在。
异常消息:
An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll
Additional information: Column 'Rule' does not belong to table SchemaTable.
我怀疑获取表模式实际上并没有给我Rule 表,而是SchemaTable。我真正想要的是与Rule 表对应的DataTable(即它具有相同的架构)。
问题:给定记录列表的行中设置列值的正确方法是什么?
【问题讨论】:
-
为什么不检查一下列名是什么?您应该能够执行类似“foreach (DataColumn col in rulesTable.Columns) { Console.WriteLine(col.Name); }”之类的操作,也许正在自动生成一个奇怪的名称。另一种选择是使用列索引。
-
rulesTable 将包含 ColumnName、ColumnOrdinal、ColumnSize、NumericPrecision 等列。它代表的是模式表,而不是表 (RuleTable) 本身。
-
@amit_g 是的,这就是我面临的问题......我如何获得实际的
RulesTable表本身? -
我注意到的另一件事。您的 SQL 查询不应返回任何内容。您选择了 TOP 0(因为没有行)。我认为您可能需要一些结果才能让 reader.GetSchemaTable() 工作。
-
您必须使用 rulesTable 中的行值动态创建表。
标签: c# sql datatable dataset datacolumn