Friday, March 12, 2010

What are relation objects in dataset and how & where to use them?

In a DataSet that contains multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table.

The following code example creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID, which serves as a link between the two DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.
custDataSet.Relations.Add("CustOrders",
custDataSet.Tables["Customers"].Columns["CustID"],
custDataSet.Tables["Orders"].Columns["CustID"]);

OR
private void CreateRelation()
{
DataColumn parentCol;
DataColumn childCol;
parentCol = custDataSet.Tables["Customers"].Columns["CustID"];
childCol = custDataSet.Tables["Orders"].Columns["CustID"];
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol);
custDataSet.Relations.Add(relCustOrder);
}

1 comment:

精采 said...
This comment has been removed by a blog administrator.