I have a adapter like this -
var ds = new DataSet("T1");
adapter.Fill(ds, "Table1");
Now, Table1 has 3 columns - Col1, Col2, Col3
I have a Table 2 with Col1 and Col3. How can I use the above adapter to Insert records for only selected columns from Table1 into Table2 ? 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'.
I have done this -
a.Initialise a SqlDataAdapter with the new Table (SELECT * FROM Table2) - call it
newAdapter
Make sure you make - AcceptChangesDuringFill = false because, later, while enumerating rows, setting the rowstate to added will not work otherwise.
b.Remove the unwanted column from the data table of Table1
c.Update the row state of this data table to 'Added' like this -
// 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. like this -
var recordsInserted = newAdapter.Update(dtTable1); // insert happens
精彩评论