Constraint Object Overview
The System.Data.Constraint type is an abstract
class with two derived classes: UniqueConstraint
and ForeignKeyConstraint. In order to use a
constraint, you must create the appropriate class and add it to the
DataTable.Constraints collection.
Constraints are enforced only if the
EnforceConstraints
property of the containing
DataSet is true, which it is by
default. If you attempt to modify, delete, or insert data in such a
way that it violates an existing constraint, and
EnforceConstraints is true, a
ConstraintException
is thrown, and the change is rejected.
Similarly, if the DataTable already contains data,
and you add a new Constraint, all the rows are
checked to ensure they agree with the new rule. If any row violates
the constraint, an InvalidConstraintException is
thrown, and the Constraint object
isn’t added.
Here are a few more rules of thumb that come into play when working
with Constraint objects:
If you have set
DataSet.EnforceConstraintstofalse, you will never encounter aConstraintExceptionorInvalidConstraintException. However, if you later changeDataSet.EnforceConstraintstotrue, all the rows will be examined to ensure that they don’t violate the existing constraints. If a discrepancy is found, anInvalidConstraintExceptionis thrown, andEnforceConstraintsis set tofalse.When merging a
DataSet, constraints are applied and verified after the merge is complete.There is no limit to how many
Constraintobjects aDataTablecan contain; you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access