我使用以下代码从DB表中获取列数据 当我检查调试模式时,我看到我在每次迭代中获得正确的表名 但对于所有表格,我获得相同属性,这是第一个表格属性
我在这里失踪了什么?
foreach (System.Data.DataRow row in schema.Rows)
{
currentTableName = row["TABLE_NAME"].ToString();
currentTableName = currentTableName = currentTableName.Replace(" ", "");
currentTableName = currentTableName.Replace("[", "");
currentTableName = currentTableName.Replace("]", "");
command.CommandText = selectQuery.Replace("@tableName", row["TABLE_NAME"].ToString());
ad.FillSchema(ds, SchemaType.Mapped, row["TABLE_NAME"].ToString());
foreach (DataColumn dc in ds.Tables[0].Columns)
{
var typeName = dc.DataType.Name;
var propName = dc.ColumnName.Replace(dc.ColumnName[0].ToString(), dc.ColumnName[0].ToString().ToLower());
propName = propName.Replace(" ", "");
}
答案 0 :(得分:0)
问题:您总是使用以下声明使用相同的表格(第一张表格):
foreach (DataColumn dc in ds.Tables[0].Columns)
上述语句中的 Tables[0]
始终引用DataSet
中的第一个表。
解决方案1:
您必须将索引值从0
更改为当前table index
。
您可以为每次迭代保留index
变量和increment
。
试试这个:
int index=0;
foreach (System.Data.DataRow row in schema.Rows)
{
currentTableName = row["TABLE_NAME"].ToString();
currentTableName = currentTableName = currentTableName.Replace(" ", "");
currentTableName = currentTableName.Replace("[", "");
currentTableName = currentTableName.Replace("]", "");
command.CommandText = selectQuery.Replace("@tableName", row["TABLE_NAME"].ToString());
ad.FillSchema(ds, SchemaType.Mapped, row["TABLE_NAME"].ToString());
foreach (DataColumn dc in ds.Tables[index].Columns)
{
var typeName = dc.DataType.Name;
var propName = dc.ColumnName.Replace(dc.ColumnName[0].ToString(), dc.ColumnName[0].ToString().ToLower());
propName = propName.Replace(" ", "");
}
index++;
}
解决方案2:您可以提供新的TableName
for-each
次迭代
试试这个:
foreach (System.Data.DataRow row in schema.Rows)
{
currentTableName = row["TABLE_NAME"].ToString();
currentTableName = currentTableName = currentTableName.Replace(" ", "");
currentTableName = currentTableName.Replace("[", "");
currentTableName = currentTableName.Replace("]", "");
command.CommandText = selectQuery.Replace("@tableName", row["TABLE_NAME"].ToString());
ad.FillSchema(ds, SchemaType.Mapped, row["TABLE_NAME"].ToString());
foreach (DataColumn dc in ds.Tables[row["TABLE_NAME"].ToString()].Columns)
{
var typeName = dc.DataType.Name;
var propName = dc.ColumnName.Replace(dc.ColumnName[0].ToString(), dc.ColumnName[0].ToString().ToLower());
propName = propName.Replace(" ", "");
}
}