Creating a Foreign Key Constraint
You can use constraints to enforce restrictions on the data in a DataTable , in order to maintain the integrity of the data. A ForeignKeyConstraint can restrict, as well as propagate, changes to related columns.
Following example shows how to create a Foreign Key Constraint
using System;
using System.Data;
namespace CreateForeignKeyConstraint
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
// Create the parent table and add to the DataSet
DataTable objCustomer = new DataTable("Customer");
objCustomer.Columns.Add("CustomerID", typeof(int));
objCustomer.Columns.Add("CustomerName", typeof(string));
ds.Tables.Add(objCustomer);
// Create the child table and add to the DataSet
DataTable objOrder = new DataTable("Order");
objOrder.Columns.Add("OrderID", typeof(int));
objOrder.Columns.Add("CustomerID", typeof(int));
objOrder.Columns.Add("Product", typeof(string));
ds.Tables.Add(objOrder);
// Create the foreign key constraint and add to the child table
ForeignKeyConstraint fk = new ForeignKeyConstraint(
"ForeignKey", objCustomer.Columns["CustomerID"], objOrder.Columns["CustomerID"]);
objOrder.Constraints.Add(fk);
try
{
// Add records to Customer table
objCustomer.Rows.Add(new object[] { 1, "Mukesh Kumar" });
objCustomer.Rows.Add(new object[] { 2, "Sunil kumar" });
//Add records to Order Table
objOrder.Rows.Add(new object[] { 10, 1, "Digital Camara" });
objOrder.Rows.Add(new object[] { 11, 2, "Mobile" });
objOrder.Rows.Add(new object[] { 12, 1, "Bluetooth Watch" });
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}\n", ex.Message);
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
}

Join the conversation! Your thoughts help the community grow.