Why does neither a DataTable.Rows[i].Delete() nor a DataSet.AcceptChanges() seem to trigger the DataRelation?

69 Views Asked by At

I have created a relation between two tables, in order for one table's rows to be protected from deletion, but this seems not to work:

My DB structure contains two tables, Areas and Locations. The Areas table has an Id column, while the Locations table has an AreaId column, serving as a foreign key.

I create a DataRelation, containing that foreign key, and now I would like to see what happens when I try to delete an Area whose Id is used as an AreaId, I though this to be straightforward:

using (var da = new SqlDataAdapter("SELECT * FROM Locations", DbConnection))
{  da.Fill(dt_Locations);  }
using (var da = new SqlDataAdapter("SELECT * FROM Areas", DbConnection))
{  da.Fill(dt_Areas);  }

dataSet.Tables.Add(dt_Locations);
dataSet.Tables.Add(dt_Areas);
DataRelation dr = new DataRelation("Locations_Areas", 
                                   dt_Areas.Columns["Id"],
                                   dt_Locations.Columns["AreaId"]);

dataSet.Relations.Add(dr);

dt_Areas.Rows[0].Delete();
dataSet.AcceptChanges();

I was expecting to get some form of Exception, either from the Delete() or from the AcceptChanges() methods, but I get nothing.

For your information: the most typical error is swapping parent and child in a DataRelation. I have replaced dt_Areas.Rows[0].Delete(); by dt_Locations.Rows[0].Delete();, but that apparently was not the cause of the issue.

The whole intention is to have something like:

try
{
  dt_Areas.Rows[i].Delete();
}
catch (Exception ex)
{
  if <ex says that "Delete()" is not permitted because of the DataRelation>
  {
    statusBar.Text = "<information over ex, dt_Areas, ...>";
  }
}

By the way, I also expected dataSet.AcceptChanges() to actually modify the database it's connected to, but nothing seems to have happened over there. Do I need to do something more besides AcceptChanges()?

Edit
Adding the following lines to my code solved the issue:

ForeignKeyConstraint fkC = 
  new ForeignKeyConstraint(dt_Areas.Columns["Id"],
                           dt_Locations.Columns["AreaId"]);
fkC.DeleteRule = Rule.None;
fkC.UpdateRule = Rule.None;
dt_Locations.Constraints.Add(fkC);
0

There are 0 best solutions below