繁体   English   中英

ADO.NET-使用Adapter.Update()插入父表中的列的子集

[英]ADO.NET - Insert using Adapter.Update() with a subset of columns from Parent Table

我有这样的适配器-

var ds = new DataSet("T1");
adapter.Fill(ds, "Table1");

现在,表1具有3列-Col1,Col2,Col3

我有带有Col1和Col3的表2。 如何使用上面的适配器将表1中 选定列的记录插入表2中? 我尝试过,但是没有运气。

// remove the column which is not required
ds.Tables["Table1"].Columns.Remove("Col2");

// clear the old table mappings
adapter.TableMappings.Clear();

// create new table mappings
DataTableMapping mapping = adapter.TableMappings.Add("Table2", ds.Tables["Table1"].ToString());
mapping.ColumnMappings.Add("Col1", ds.Tables["Table1"].Columns[0].ColumnName);
mapping.ColumnMappings.Add("Col3", ds.Tables["Table1"].Columns[2].ColumnName);

// fill the adapter with new Dataset
var newDs = ds.Copy();
adapter.Fill(newDs);
ds.Dispose();

// Insert records into new Table
recordsUpdated += adapter.Update(newDs , "Table2");

错误-其他信息:缺少源列'Col2'的数据表'Table1'中的数据列'Col2'。

我已经做到了-

用新表初始化SqlDataAdapter(SELECT * FROM Table2)-调用它

newAdapter

确保您使-AcceptChangesDuringFill = false,因为稍后在枚举行时,将rowstate设置为添加将无法正常工作。

b。从表1的数据表中删除不需要的列

c。将此数据表的行状态更新为“已添加”,如下所示:

// 1st, commit all changes in the DataTable.
dtTable1.AcceptChanges();

// update the row state
foreach (DataRow row in dtTable1.Rows)
{
  row.SetAdded();
}

d。最后使用在步骤a中创建的适配器“插入”。 像这样 -

var recordsInserted = newAdapter.Update(dtTable1); // insert happens

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM