Update not taking effect on SQLCe 3.5 with dataset

2019-08-06 04:24发布

问题:

We used the VS2010 data connection design wizard to define a connection to a SQLCe database with just one table (database="UserMetrics" table="User"). Try as we might the update doesn't seem to hold, I've been through posts on SO and MSDN but can't see the glaring error...

        //initialize 
        UserMetricsDataSet umDataSet = new UserMetricsDataSet( );
        UserMetricsDataSetTableAdapters.UserTableAdapter umTableAdapter = new    UserMetricsDataSetTableAdapters.UserTableAdapter( );

        // check that test data is there and count is correct
        umTableAdapter.Fill( umDataSet.User );
        UserMetricsDataSet.UserRow umRow = (UserMetricsDataSet.UserRow)umds.User.Rows[0]; 
        int count = umDataSet.User.Rows.Count; //yep its there

        //lets add some rows
        for (int i = 0; i < 100; i++)
            umDataSet.User.AddUserRow( "smith", (float)54, (float)3, 1);

        umds.User.AcceptChanges( );
        //umTableAdapter.Update(umDataSet.User); //tried this also ... no change...

        // there are now 101 rows !!
        int count = umDataSet.User.Rows.Count; //yep its there
        umRow = (UserMetricsDataSet.UserRow)umds.User.Rows[101];

        //lets double check
        umTableAdapter.Fill( umDataSet.User );
        int count = umds.UserMetris.Rows.Count; //huh!!! count==1 ???

回答1:

I'm assuming umDataSet is the same thing as umds.

What about?

UserMetricsDataSet.UserRow umRow = umDataSet.User.NewRow();
umRow["Name"] = "smith";
// etc
umDataSet.User.ImportRow(umRow);
umDataSet.User.AcceptChanges();

Or what about reversing the order? The TableAdapter.Update() method sends updates back to the database based on the changes in the DataTable. If you accept the changes first, then the RowState is reset on each DataTable row, so there are no updates found to send back to the database.

From MSDN:

In order to send the modified data to a database, you call the Update method of a TableAdapter. The adapter's Update method will update a single data table and execute the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.

try
{
    umTableAdapter.Update(umDataSet.User);
    umDataSet.User.AcceptChanges();
}
catch (Exception ex)
{
    // TableAdapter.Update() can throw exceptions
}