Updating using SqlDataAdapter and DataSet

39 views Asked by At

I have a DataSet (named newDataSet) obtained from an XML file

DataSet newDataSet = new DataSet(); 
newDataSet.Tables.Add(table);

And I have a DataSet (named dataSetFromDb) obtained from a SQL Server database.

DataSet dataSetFromDb = new DataSet();
SqlCommand sql = new SqlCommand($"SELECT * FROM {table.TableName}", Connection);
SqlDataAdapter adapter = new SqlDataAdapter(sql);
adapter.Fill(dataSetFromDb);

These two data sets (newDataSet and dataSetFromDb) are completely consistent in their structure.

Moreover, they contain identical records with the same Id. My task is to update the corresponding table in the database with records from newDataSet. And I do this

SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);

adapter.UpdateCommand = commandBuilder.GetUpdateCommand();

dataSetFromDb.Merge(newDataSet); 

adapter.Update(dataSetFromDb, table.TableName);

The code runs successfully, but the data in the database does not change. Under the debugger I see that dataSetFromDb.Merge(newDataSet); doesn't work because no data is added.

If I write dataSetFromDb = newDataSet; then I get the exception

Update unable to find TableMapping['Table'] or DataTable 'Table'.

If I write adapter.Update(dataSetFromDb, table.TableName); then the exception:

"PK_AddHouseTypes" PRIMARY KEY constraint is violated is raised. Cannot insert a duplicate key into an object

In addition, since there is a lot of data in some tables, the following code

DataSet dataSetFromDb = new DataSet();
SqlCommand sql = new SqlCommand($"SELECT * FROM {table.TableName}", Connection);
SqlDataAdapter adapter = new SqlDataAdapter(sql);
adapter.Fill(dataSetFromDb);

takes a very long time to complete

Please Tell me how I can update the tables in the database.

0

There are 0 answers