Given a DataTable
loaded with some data how can it be reused to perform multiple inserts into different SQL Server database tables using different SqlDataAdapter.Update()
methods?
After using the DataTable
to insert records into table 1, a different SqlDataAdapter
will not insert data into table 2 and Update()
method always returns 0 without throwing an exception.
I tried using the Copy()
and RejectChanges()
methods of the DataTable
but it never inserts data into table 2.
Some code:
var dataAdapter1 = new SqlDataAdapter
{
UpdateBatchSize = updateBatchSize,
InsertCommand = new SqlCommand(insertCommand1, dbConnection)
{
UpdatedRowSource = UpdateRowSource.None
}
};
dataAdapter1 .InsertCommand.Parameters.Add("@Id", SqlDbType.Int, 0, "Id");
dbConnection.Open();
dataAdapter1 .Update(dtSomeDataTable);
// This inserts data into table 1.
var dataAdapter2 = new SqlDataAdapter
{
UpdateBatchSize = updateBatchSize,
InsertCommand = new SqlCommand(insertCommand2, dbConnection)
{
UpdatedRowSource = UpdateRowSource.None
}
};
var count = dataAdapter2.Update(dtSomeDataTable);
//This does not insert any records (or throws an exception) and variable count is always 0;
Take a look at this MSDN post to understand the concept of DataRow.RowState: https://msdn.microsoft.com/en-us/library/ww3k31w0(v=vs.110).aspx
When you call Update on the first SqlAdapter, all rows are marked as Unchanged and subsequent Update calls won't consider them anymore.
You could try "touching" each row by reading a value from one of the columns and setting that same value. Maybe that will cause the RowState to switch to Modified so that the second Update operation acts on all rows again.
Maybe try calling SetAdded on each DataRow, before the 2nd call to Update ?
https://msdn.microsoft.com/en-us/library/system.data.datarow.setadded%28v=vs.110%29.aspx
通过保持原始DataTable
不变并使用DataTable.Copy()
方法创建的每个必需更新来处理副本来解决...如果发布了更好的答案,我将接受它...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.