问题描述
此代码段引发错误:
更新无法在适配器上找到 TableMapping['Table'] 或 DataTable 'Table'.).Update(ds);线
Update unable to find TableMapping['Table'] or DataTable 'Table'.) on adapter.Update(ds); line
为什么会抛出这种类型的错误?
Why it is throwing this type of error?
SqlConnection con = new SqlConnection();
con.ConnectionString = connectionString();
DataSet ds = new DataSet();
string strQuery = "SELECT * FROM Cars";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(strQuery, con);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(ds, "Cars");
//Code to modify data in the DataSet
ds.Tables["Cars"].Rows[0]["Brand"] = "NewBrand";
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(ds);
推荐答案
使用
adapter.Update(ds, "Cars");
改为.
我已经测试过了.我得到了同样的错误,如果我指定表名,它就可以工作.但是,我必须承认我还不知道为什么 DataAdapter
需要知道表名,因为它具有所需的所有信息.如果我使用ds.GetChanges
我得到一行具有正确的表名.
I have tested it. I got the same error without and it works if i specify the tablename. However, i must admit that i yet don't know why the DataAdapter
needs to know the table-name since it has all informations it needs. If i useds.GetChanges
i get one row with the correct table-name.
更新我在 上什么也没找到MSDN 但最后在源码中找到了(ILSpy).下面是DBDataAdapter.Update(DataSet)
的实现:
public override int Update(DataSet dataSet)
{
return this.Update(dataSet, "Table");
}
因此,如果您不指定表,则使用表名 "Table"
,如果您指定了其他表名,则会出现此错误,即真奇怪!
So if you don't specify a table, the table-name "Table"
is used and if you've specified a table-name other than that you'll get this error, that's really strange!
我认为造成这种情况的原因是 DataAdapter
无法调用 GetChanges
来确定要更新的表,原因有两个:
I assume that the reason for this is that the DataAdapter
cannot call GetChanges
to determine the table to update for two reasons:
- 这将是低效的,因为它需要循环所有表及其所有行以查找具有
RowState
的行!=Unchanged
- 可能需要更新多个表,因为它们包含已更改的行.
DataAdapter
不支持.因此DataAdapter.Update(DataSet)
假定默认名称"Table"
为 table-name.
- It would be inefficient since it needs to loop all tables and all of their rows to find rows with a
RowState
!=Unchanged
- It's possible that multiple tables needs to be updated since they contain changed rows. That is not supported via
DataAdapter
. HenceDataAdapter.Update(DataSet)
assumes the default name"Table"
as table-name.
编辑:但是,也许有人可以解释一下为什么 DataAdapter
不使用 DataSet.Tables[0].TableName
代替.
Edit: However, maybe someone can explain me why the DataAdapter
doesn't use DataSet.Tables[0].TableName
instead.
所以一般来说,最好的做法是指定要更新的表的名称.
So in general it seems to be best practise to specify the name of the table you want to update.
这篇关于DataAdapter:更新无法找到 TableMapping['Table'] 或 DataTable 'Table'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!