Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a datatable from a dataset (has a bunch of relationships)

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"); 
    }
like image 547
Steve0 Avatar asked Sep 02 '11 17:09

Steve0


1 Answers

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]);
            }
        }
like image 166
Davide Piras Avatar answered Oct 06 '22 02:10

Davide Piras