As we all know Dataset plays a significant role while working with .net applications. Those who are new to dataset, it is just an in memory representation of table data. This object is sufficient to differentiate classic ADO and ADO.NET. Constraints are nothing but conditions applied to the table Column or Columns to maintain data integrity in the table. Generally we use constraints in the database tables. We can also implement Constraints in the dataset tables. There are mainly 3 types of constraints in Datasets.
Before going in depth for constraint let’s create a dataset with some tables in VB.Net Dim SqlConn As SqlConnection = New SqlConnection(“ConnString”) SqlDa = New SqlDataAdapter(“SELECT * FROM CustomerTable”, SqlConn) SqlDa = New SqlDataAdapter(“SELECT * FROM CustomerOrderTable”, SqlConn) Now we are having a dataset named SqlDs with 2 tables named CustomerTable and OrderTable. Let’s apply different constraints to these tables. |
1. UniqueKeyConstraint Dim AppTable As DataTable = SqlDs.Tables(“CustomerTable”) The Column having Unique constraint is allowed to have null values. So we can also create unique constraint as SqlDs.Tables(“CustomerTable”).Columns(“CustomerID”).Unique = True SqlDs.Tables(“CustomerTable”).Columns(“CustomerID”).AllowDBNull = True If AllowDBNull is True then null value is allowed. 2. Primary Key Constraint SqlDs.Tables(“CustomerTable”).PrimaryKey = New DataColumn(){SqlDs.Tables(“CustomerTable”).Columns(“CustomerID”)} 3. Foreign Key Constraint Cascade: Delete or update related rows. This is the default. The code here creates a ForeignKeyConstraint on CustomerOrder.CustomerKey for CustomerTable.CustomerID as PrimeryKey. Dim FornKey As ForeignKeyConstraint FornKey.DeleteRule = Rule.Cascade SqlDs.Tables(“CustomerOrder”).Constraints.Add(FornKey) The property EnforceConstraints specifies the constraint should be enforced or not. |