DataTable exception exception in RejectChanges

I found this error when working with a DataTable. I added a primary key column to the DataTable, than added one row to this table, deleted this row and added a row with the same key to the table. It works. When I tried to call RejectChanges() on it, I got a ConstraintException , saying that this value is already present. Here is an example:

  var dataTable = new DataTable(); var column = new DataColumn("ID", typeof(decimal)); dataTable.Columns.Add(column); dataTable.PrimaryKey = new [] {column }; decimal id = 1; var oldRow = dataTable.NewRow(); oldRow[column] = id; dataTable.Rows.Add(oldRow); dataTable.AcceptChanges(); oldRow.Delete(); var newRow = dataTable.NewRow(); newRow[column] = id; dataTable.Rows.Add(newRow); dataTable.RejectChanges(); // This is where it crashes 

I think that since the row is deleted, the exception should not be thrown (the restriction is not violated because the row is in the delete state). Is there anything I can do about it? Any help is appreciated.

+4
source share
2 answers

I assume this has the same reason as the following error, since the first to be rejected is your delete action:

DataTable.RejectChanges () should roll back rows in reverse order

Possible workarounds:

Loops through DataRows return them back in reverse order. So new entries are deleted before the previous ones are brought back to life.

 DataRowCollection rows = dataTable.Rows; for (int i = rows.Count - 1; i >= 0; i--) { rows[i].RejectChanges(); } 

Disables restrictions, so rollback can be performed. After that, restores the restrictions.

  • You can use LINQ-to-DataSet to define your own "rollback order":

     var rollbackPlan = (from r in dataTable.AsEnumerable() where r.RowState != DataRowState.Unchanged let firstOrder = r.RowState==DataRowState.Deleted? 1 : 0 let secondOrder = r.RowState==DataRowState.Added? 1 : 0 orderby firstOrder ascending, secondOrder ascending select r).ToList(); foreach (DataRow r in rollbackPlan) { r.RejectChanges(); // Does not crash anymore } 
  • Here you temporarily disable restrictions on the DataTable :

     var constraintBackup = dataTable.Constraints.Cast<System.Data.Constraint>().ToList(); dataTable.Constraints.Clear(); dataTable.RejectChanges(); // Does not crash anymore foreach (System.Data.Constraint c in constraintBackup) { dataTable.Constraints.Add(c); } 
+2
source

You can avoid this by using the unique property of the tor column true .

i.e. column.Unique = true;

Once this property is changed to true, a unique constraint will be created in this column to ensure that the values ​​are unique.

0
source

Source: https://habr.com/ru/post/1402201/


All Articles