Datasets in Microsoft.Net - The DataTable Object’s Constraints Collection
(Page 5 of 8 )
You can also validate data in your DataSet by setting properties of the DataTable object. The ADO.NET object model includes two classes that you can use to define constraints in a DataTable. These classes, UniqueConstraint and ForeignKeyConstraint, are derived from the Constraint class. The DataTable exposes a Constraints property that you can use to add to, modify, or examine the constraints on the DataTable.
- UniqueConstraints
If you set the Unique property of a DataColumn to True, you’ve defined a unique constraint in the DataTable that contains that column. At the same time, you’ve also added a UniqueConstraint object to the DataTable object’s Constraints collection. Setting the Unique property of a DataColumn is simpler than creating a new UniqueConstraint in a DataTable object’s Constraints collection. However, there are times when you’ll want to explicitly create a UniqueConstraint, such as when you need to make sure that the combinations of values from multiple columns are unique.
- PrimaryKey
A primary key is a special type of unique constraint. The ADO.NET DataRowCollection object has a Find method that you can use to locate a row in your DataTable by the value or values in its primary key column, as shown here. row
= MyTable.Rows.Find("RAGS")
A DataTable can have multiple unique constraints but can contain at most one primary key. You can set or examine a DataTable object’s primary key using its PrimaryKey property.
- ForeignKeyConstraint
You can also add foreign constraints to a DataTable. I described an example of a foreign key constraint just a couple pages back. Each order in the Northwind database’s Orders table must have a value for its CustomerID column that is used in the Customers table. You can place similar restrictions on the data in your DataSet by creating a ForeignKeyConstraint and adding it to the table whose rows you want to validate.
You generally won’t need to explicitly create a ForeignKeyConstraint. Creating a DataRelation between two DataTable objects within your DataSet creates a ForeignKeyConstraint in the process. In the next chapter, I’ll discuss the DataRelation object and how you can use it to work with relational data.
Next: Creating Dataset at Design Time >>
More ADO.NET Articles
More By Raghav Nayak