我正在使用 VB.NET dataAdapter 从 Oracle 数据库导入表。我使用“fill”命令将导入的数据添加到数据集。在 DataTable 已经填充了数据之后,如何将 DataTable 的特定列定义为 PrimaryKey?
最佳答案
您可以通过以下方式设置表的主键:
Dim table As New DataTable()
table.Columns.Add(New DataColumn("MyColumn"))
Dim primaryKey(1) As DataColumn
primaryKey(1) = table.Columns("MyColumn")
table.PrimaryKey = primaryKey
为了能够使用主键,您需要确保给定列的所有值都是唯一的。
我主要在 C# 中工作,并且有几个扩展方法用于“整理”我需要进行的调用,您可能需要考虑将其转换为 VB 并使用:
public static void SetPrimaryKey(this DataTable value, string columnName)
{
value.PrimaryKey = new DataColumn[] { value.Columns[columnName] };
}
public static DataRow FindByPrimaryKey(this DataTable value, object key)
{
return value.Rows.Find(key);
}
// I can then do:
DataTable table = CallToRoutineThatGetsMyDataTable();
table.SetPrimaryKey("PKColumnName");
DataRow result = table.FindByPrimaryKey("valueToFindWith");
关于vb.net - 如何在创建后将 VB.NET DataTable Column 定义为主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2470681/