The System.Data DataRelation class is a part of the .NET framework which helps to define a relationship between two DataTable objects. It is used to create a parent-child relationship between two DataTables so that when a parent data row is deleted, its associated child rows are deleted automatically.
Example 1:
Suppose we have two DataTables - Customers and Orders. One customer can have multiple orders, so we can create a relationship between the two tables as follows:
//Creating relation between Customers and Orders DataTables DataRelation dataRel = new DataRelation("CustomersOrdersRelation", Customers.Columns["CustomerId"], Orders.Columns["CustomerId"]); dataSet.Relations.Add(dataRel);
Here, we create a DataRelation object named CustomersOrdersRelation and define it by passing the column name in the Customers and Orders tables that establishes the relationship.
Example 2:
Suppose we have a database with three tables - employee, department, and project. There are multiple employees in a department and multiple projects in a department. We can create two relations in this scenario - one between employee and department and another between project and department.
//Creating relation between Department and Employee DataTables DataRelation dataRel1 = new DataRelation("DepartmentEmployeeRelation", Department.Columns["DepartmentId"], Employee.Columns["DepartmentId"]); dataSet.Relations.Add(dataRel1);
//Creating relation between Department and Project DataTables DataRelation dataRel2 = new DataRelation("DepartmentProjectRelation", Department.Columns["DepartmentId"], Project.Columns["DepartmentId"]); dataSet.Relations.Add(dataRel2);
Here, we create two DataRelation objects named DepartmentEmployeeRelation and DepartmentProjectRelation, and define them by passing the column name in the corresponding tables that establishes the relationship.
The package library for System.Data.DataRelation is part of the .NET Framework.
C# (CSharp) System.Data DataRelation - 60 examples found. These are the top rated real world C# (CSharp) examples of System.Data.DataRelation extracted from open source projects. You can rate examples to help us improve the quality of examples.