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

查看:684
本文介绍了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!= Unchanged
  2. 的行
  3. 由于多个表包含已更改的行,因此可能需要对其进行更新.通过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天全站免登陆