本文整理汇总了C#中System.Data.UniqueConstraint.UniqueConstraint构造函数的典型用法代码示例。如果您正苦于以下问题:C# UniqueConstraint构造函数的具体用法?C# UniqueConstraint怎么用?C# UniqueConstraint使用的例子?那么恭喜您, 这里精选的构造函数代码示例或许可以为您提供帮助。
在下文中一共展示了UniqueConstraint构造函数的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MakeTableWithUniqueConstraint
static private void MakeTableWithUniqueConstraint()
{
// Create a DataTable with 2 DataColumns.
DataTable dataTable = new DataTable("dataTable");
DataColumn idColumn = new DataColumn(
"id", System.Type.GetType("System.Int32"));
DataColumn nameColumn = new DataColumn(
"Name", System.Type.GetType("System.String"));
dataTable.Columns.Add(idColumn);
dataTable.Columns.Add(nameColumn);
// Run procedure to create a constraint.
AddUniqueConstraint(dataTable);
// Add one row to the table.
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["id"] = 1;
dataRow["Name"] = "John";
dataTable.Rows.Add(dataRow);
// Display the constraint name.
Console.WriteLine(
dataTable.Constraints[0].ConstraintName);
// Try to add an identical row,
// which throws an exception.
try
{
dataRow = dataTable.NewRow();
dataRow["id"] = 1;
dataRow["Name"] = "John";
dataTable.Rows.Add(dataRow);
}
catch (Exception ex)
{
Console.WriteLine(
"Exception Type: {0}", ex.GetType());
Console.WriteLine(
"Exception Message: {0}", ex.Message);
}
}
static private void AddUniqueConstraint(
DataTable dataTable)
{
// Create the DataColumn array.
DataColumn[] dataColumns = new DataColumn[2];
dataColumns[0] = dataTable.Columns["id"];
dataColumns[1] = dataTable.Columns["Name"];
// Create the constraint on both columns.
UniqueConstraint uniqueConstraint =
new UniqueConstraint("idNameConstraint", dataColumns);
dataTable.Constraints.Add(uniqueConstraint);
}