Search code examples
c#sql-serverdatatabledatarowtableadapter

Datatable won't update my DB


usersTableAdapter usersTA = new usersTableAdapter();
var usersTable = new users.usersDataTable();
usersTA.Fill(usersTable);

VK_BDayParser.users.usersRow row = usersTable.FindByid(currentItem.id);
row.BeginEdit();
row.last_name = "********";
row.EndEdit();

row.AcceptChanges();
usersTable.AcceptChanges();

int result = usersTA.Update(usersTable);

SQL server 2012.

I used generated classes from VS 2013 to database

I try to update row in my DB, in 'usersRow row' this changes works, but in DB has no changes. What am I doing wrong? result is always 0.


Solution

  • This is a common misunderstanding on what the AcceptChanges method does.
    I think the problem arises from the initial comment in the documentation of the AcceptChanges method .

    Commits all the changes made to this table since the last time AcceptChanges was called.

    Many people think that this means 'commits to the database table', instead it means 'commits to the in-memory instance of the datatable object'.

    Then, the following comment on the docs, hints to what is really happening there.

    When AcceptChanges is called, any DataRow object still in edit mode successfully ends its edits. The DataRowState also changes: all Added and Modified rows become Unchanged, and Deleted rows are removed.

    So, there is this DataRow.RowState property that express what is the current state of the in-memory rows belonging to the in-memory instance of the DataTable. And it is this state that helps the DataAdapter.Update method in discovering what to do with the rows.

    In other words the Update method decides to update the database table only for the rows that are not RowState==DataRowState.Unchanged. But calling AcceptChanges 'commits' these rows and their state becomes Unchanged. No update then.