I am attempting to remove a datatable that was loaded into a dataset, and has been related. Here is the code I attempted.
domain.EnforceConstraints = false;
if (domain.Tables["TABLE_NAME"] != null)
{
domain.Tables["TABLE_NAME"].ChildRelations.Clear();
domain.Tables["TABLE_NAME"].ParentRelations.Clear();
domain.Tables.Remove("TABLE_NAME");
}
domain.EnforceConstraints = true;
This throws an exception at the point of removing the table, due to a foreign-key constraint existing. Unfortunately, the way the logic is I have no idea what the name of the constraint is [so I cannot hard code it].
Is there away to accomplish this in an easier fashion, or can I get some suggestions as to how to locate and remove the constraint that is causing my issue.
Thanks in advance, Steve
--------------------------ANSWER------------------------
I wasn't allowed to answer my own question so here is the solution I came up with. This code snippet now works for me. I had to travel the relation to the other table and remove the constraint from there.
if (domain.Tables["TABLE_NAME"] != null)
{
for (int f = domain.Tables["TABLE_NAME"].ChildRelations.Count -1; f >=0; f--)
{
domain.Tables["TABLE_NAME"].ChildRelations[f].ChildTable.Constraints.Remove(domain.Tables["TABLE_NAME"].ChildRelations[f].RelationName);
domain.Tables["TABLE_NAME"].ChildRelations.RemoveAt(f);
}
domain.Tables["TABLE_NAME"].ChildRelations.Clear();
domain.Tables["TABLE_NAME"].ParentRelations.Clear();
domain.Tables["TABLE_NAME"].Constraints.Clear();
domain.Tables.Remove("TABLE_NAME");
}
before you remove the table from the dataset try to clear all its constaints, something like this:
domain.Tables["TABLE_NAME"].Constraints.Clear();
should work and you should then be able to remove it from the dataset.
if you have the issue with PK Constraint which cannot be removed try this:
var myTable = domain.Tables["TABLE_NAME"];
for (int i = myTable.Constraints.Count - 1; i >= 0; --i)
{
if (myTable.Constraints[i] is System.Data.ForeignKeyConstraint)
{
myTable.Constraints.Remove(myTable.Constraints[i]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With