DataAdapter:更新无法找到TableMapping [' Table']或DataTable' Table' [英] DataAdapter: Update unable to find TableMapping['Table'] or DataTable 'Table'

查看:96
本文介绍了DataAdapter:更新无法找到TableMapping [' Table']或DataTable' Table'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码段引发错误:

更新无法在adapter.Update(ds)上找到TableMapping ['Table']或DataTable'Table'.);线

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:

  1. 效率低下,因为它需要循环所有表及其所有行以查找具有 RowState 的行!= 未更改
  2. 由于多个表包含已更改的行,因此可能需要对其进行更新.通过 DataAdapter 不支持.因此, DataAdapter.Update(DataSet)假定默认名称"Table" 作为表名.
  1. It would be inefficient since it needs to loop all tables and all of their rows to find rows with a RowState != Unchanged
  2. It's possible that multiple tables needs to be updated since they contain changed rows. That is not supported via DataAdapter. Hence DataAdapter.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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆