Domanda

Somewhat confused here, the following code causes changes in the DataTable when I would not expect it to do so. Is there no actual individual value change management inside of a DataTable? Or am I missing something?

var table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Rows.Add("Sample Name");
table.AcceptChanges();

table.Rows[0].SetField("Name", "Sample Name");

var changes = table.GetChanges();

// expecting null, actually returns changes

I would have expected internally the table to use some pre-built logic to determine whether or not the new value is indeed different from the current value.

Why is it done like this?

È stato utile?

Soluzione

When you modify content of a row, it updates the DataRow.RowState property, which can hold UnChanged, Added, Modified etc. Later DataTable.GetChanges filter out rows based on that row status. It is irrespective of the value.

DataTable.GetChanges - MSDN

Gets a copy of the DataTable containing all changes made to it since it was last loaded, or since AcceptChanges was called, filtered by DataRowState.

Also see:

Row States and Row Versions - MSDN

ADO.NET manages rows in tables using row states and versions. A row state indicates the status of a row; row versions maintain the values stored in a row as it is modified, including current, original, and default values. For example, after you have made a modification to a column in a row, the row will have a row state of Modified, and two row versions: Current, which contains the current row values, and Original, which contains the row values before the column was modified.

Altri suggerimenti

This is apparently a design feature as even calling the SetField() extension method with exactly the same object and then checking the field values in DataRowVersion.Original and DataRowVersion.Current you can find that they are still reference equal. There is no documentation describing a different behavior.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top