Ravi
Ravi

Reputation: 105

How to remove constraints from datatable in .NET?

I cannot set any constraints in my datatable if i merge two datatables dt1.Merge(dt2); It shows error like this Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. By default i view in visualizer it shows constraints count as 2. How to remove constraints from datatable and solve this error?

Upvotes: 7

Views: 27871

Answers (4)

Yemoku
Yemoku

Reputation: 126

Alternatively, you can also do

New DataView(dt).ToTable

to create a copy of the table without constraints

Upvotes: 3

Peter Meinl
Peter Meinl

Reputation: 2586

To remove constraints from a DataTable you can use the Clear method of the Constrains property:

myDataTable.Constraints.Clear();

Upvotes: 13

S2S2
S2S2

Reputation: 8502

EDIT:

Ok this is more clear now: You can't remove constraints, they are disable during merge operation and then automatically enable after the merge if they can be enabled.

As the error is like after the merge operation is completed, the Constraints can't be enabled due to some of the invalid values in target datatable. So, I think you would need to explicitly update the target datatable dt2 values before the merge operation starts. This can be done by watching the constraints in datatable dt1 and resolving those contraints in datatable dt2 with code (by updating the null or non-unique or foriegn key data in target datatable dt2); and then start the merge operation.

The following excerpt and link from MSDN explains this while doing the Merge operation:

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

http://msdn.microsoft.com/en-us/library/803bh6bc.aspx

Upvotes: 1

Shoaib Shaikh
Shoaib Shaikh

Reputation: 4585

try iterating the constraints of datatable and remove them using

private void RemoveConstraint(DataTable table, 
    Constraint constraint)
{
    if(table.Constraints.Contains(constraint.ConstraintName))
        if(table.Constraints.CanRemove(constraint))
            table.Constraints.Remove(constraint);
}

Upvotes: 3

Related Questions