[英]ADO.NET - Insert using Adapter.Update() with a subset of columns from Parent Table
I have a adapter like this - 我有这样的适配器-
var ds = new DataSet("T1");
adapter.Fill(ds, "Table1");
Now, Table1 has 3 columns - Col1, Col2, Col3 现在,表1具有3列-Col1,Col2,Col3
I have a Table 2 with Col1 and Col3. 我有带有Col1和Col3的表2。 How can I use the above adapter to Insert records for only selected columns from Table1 into Table2 ? 如何使用上面的适配器将表1中仅 选定列的记录插入表2中? I tried this, but no luck. 我尝试过,但是没有运气。
// 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");
ERROR - Additional information: Missing the DataColumn 'Col2' in the DataTable 'Table1' for the SourceColumn 'Col2'. 错误-其他信息:缺少源列'Col2'的数据表'Table1'中的数据列'Col2'。
I have done this - 我已经做到了-
a.Initialise a SqlDataAdapter with the new Table (SELECT * FROM Table2) - call it 用新表初始化SqlDataAdapter(SELECT * FROM Table2)-调用它
newAdapter
Make sure you make - AcceptChangesDuringFill = false because, later, while enumerating rows, setting the rowstate to added will not work otherwise. 确保您使-AcceptChangesDuringFill = false,因为稍后在枚举行时,将rowstate设置为添加将无法正常工作。
b.Remove the unwanted column from the data table of Table1 b。从表1的数据表中删除不需要的列
c.Update the row state of this data table to 'Added' like this - c。将此数据表的行状态更新为“已添加”,如下所示:
// 1st, commit all changes in the DataTable.
dtTable1.AcceptChanges();
// update the row state
foreach (DataRow row in dtTable1.Rows)
{
row.SetAdded();
}
d.Finally 'insert' using the adapter created in Step a. d。最后使用在步骤a中创建的适配器“插入”。 like this - 像这样 -
var recordsInserted = newAdapter.Update(dtTable1); // insert happens
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.