Handle constraint exceptions in datagrid

2019-08-08 14:14发布

问题:

I am busy adding database (SQLite) support to my latest application. Since there are some tables that has rows that reference rows in other tables I thought it might be a good idea to start using foreign key constraints. A few google searches later I was able to apply the constraints to one table as a test run.

var c = workingDataSet.Tables["measurements"].Columns["reference_realestate"];
var p = workingDataSet.Tables["realestates"].Columns["id"];

ForeignKeyConstraint fkcon = new ForeignKeyConstraint(p, c);
fkcon.DeleteRule = Rule.None;                

workingDataSet.Tables["measurements"].Constraints.Add(fkcon);

This works, if I try to remove a "realestates" record that is referenced in "measurements" the following exception is raised:

'An unhandled exception of type 'System.Data.InvalidConstraintException' occurred in System.Data.dll Additional information: Cannot delete this row because constraints are enforced on relation Constraint1, and deleting this row will strand child rows.'

My problem now is where and how do I handle this exception? After reading some other posts I found this which points me to handle the exception in the DataGrid control. I have tried using RowValidationRules but it doesn't seem to work either.

<DataGrid.RowValidationRules>
    <local:RowValidation_Measurements ValidationStep="UpdatedValue"/>
</DataGrid.RowValidationRules>

Any ideas how I can achieve this? Oh, and I have to mention I am using MVVM.