技术文章 > C#DATATABLE数据表之约束CONSTRAINT的使用方法

C#DATATABLE数据表之约束CONSTRAINT的使用方法

2018-11-14 15:19

文档管理软件,文档管理系统,知识管理系统,档案管理系统的技术资料:
约束是用于维护 DataTable 中的数据的完整性的规则。例如,当删除在一个或多个相关表中使用的值时,ForeignKeyConstraint 确定如何处理相关表中的值:同样删除、设置为空值、设置为默认值或者不执行任何操作。另一方面,UniqueConstraint 只是确保特定的表内的所有值都是唯一的。有关更多信息,请参见 将约束添加到表。
不使用基本的 Constraint 构造函数。使用 UniqueConstraint 构造函数创建主键约束或唯一键约束,使用 ForeignKeyConstraint 构造函数创建外键约束。

下面的示例检查 DataTable 的约束集合,并确定每个约束是 UniqueConstraint 还是 ForeignKeyConstraint。然后显示约束的属性。

private void GetConstraints(DataTable dataTable)
{
Console.WriteLine();

// Print the table“s name.
Console.WriteLine(“TableName: “ + dataTable.TableName);

// Iterate through the collection and
// print each name and type value.
foreach(Constraint constraint in dataTable.Constraints )
{
Console.WriteLine(“Constraint Name: “
+ constraint.ConstraintName);
Console.WriteLine(“Type: “
+ constraint.GetType().ToString());

// If the constraint is a UniqueConstraint,
// print its properties using a function below.
if(constraint is UniqueConstraint)
{
PrintUniqueConstraintProperties(constraint);
}
// If the constraint is a ForeignKeyConstraint,
// print its properties using a function below.
if(constraint is ForeignKeyConstraint)
{
PrintForeigKeyConstraintProperties(constraint);
}
}
}

private void PrintUniqueConstraintProperties(
Constraint constraint)
{
UniqueConstraint uniqueConstraint;
uniqueConstraint = (UniqueConstraint) constraint;

// Get the Columns as an array.
DataColumn[] columnArray;
columnArray = uniqueConstraint.Columns;

// Print each column“s name.
for(int i = 0;i<columnArray.Length ;i++)
{
Console.WriteLine(“Column Name: “
+ columnArray[i].ColumnName);
}
}

private void PrintForeigKeyConstraintProperties(
Constraint constraint)
{
ForeignKeyConstraint fkConstraint;
fkConstraint = (ForeignKeyConstraint) constraint;

// Get the Columns as an array.
DataColumn[] columnArray;
columnArray = fkConstraint.Columns;

// Print each column“s name.
for(int i = 0;i<columnArray.Length ;i++)
{
Console.WriteLine(“Column Name: “
+ columnArray[i].ColumnName);
}
Console.WriteLine();

// Get the related columns and print each columns name.
columnArray = fkConstraint.RelatedColumns ;
for(int i = 0;i<columnArray.Length ;i++)
{
Console.WriteLine(“Related Column Name: “
+ columnArray[i].ColumnName);
}
Console.WriteLine();
}