我正在使用VB.NET dataAdapter从Oracle数据库导入表。我使用“填充”命令将导入的数据添加到数据集中。在数据表已填充数据后,如何将数据表的特定列定义为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");
只要该列中的值是唯一的
table.PrimaryKey = new DataColumn[] { table.Columns["Id"] };
调整您的列名。
这里是VB的一线工具(问题在于“使用VB.NET”)。这个例子有两列索引:
table.PrimaryKey = New DataColumn() {table.Columns("column1"), _
table.Columns("column2")}
更新:这是关于如何使用这2列索引查找行的另一种方法:
table.Rows.Find(New Object() {value1, value2}) '<- DataRow returned
更新2:以及如何使用主键查找已经填充了数据的DataTable的完整示例:
'Define primary keys (you do this only once)
table.PrimaryKey = New DataColumn() {table.Columns("column1"), _
table.Columns("column2")}
'Find a row:
Dim MyDataRow As DataRow
MyDataRow = table.Rows.Find(New Object() {value1, value2}) '<- DataRow returned
If MyDataRow IsNot Nothing Then 'If a row is found
Return MyDataRow.Item("column3")
End If
感谢答案Rob-尽管vb版本的索引应该从零开始,但是vb版本还是有一个小问题:
Dim table As New DataTable()
table.Columns.Add(New DataColumn("MyColumn"))
Dim primaryKey(1) As DataColumn
primaryKey(0) = table.Columns("MyColumn")
table.PrimaryKey = primaryKey