.net 将现有列标记为数据表中的主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3621721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
marking existing column as primary key in datatable
提问by NoviceToDotNet
I have a datatable from database on the basis of some query.
我有一个基于某些查询的数据库数据表。
I want that datatable to have a primary key for an existing column.
我希望该数据表具有现有列的主键。
How can I do this?
我怎样才能做到这一点?
回答by dcp
Assuming the name of the column in your data table you want to be the primary key is called pk_column, you could do this (assume dtis your DataTable):
假设你的数据表中你想要成为主键的列的名称被称为pk_column,你可以这样做(假设dt是你的DataTable):
dt.PrimaryKey = new DataColumn[] { dt.Columns["pk_column"] };
If your primary key is made up of multiple columns, you can add them to the array, like so:
如果您的主键由多列组成,您可以将它们添加到数组中,如下所示:
dt.PrimaryKey = new DataColumn[] { dt.Columns["pk_column1"], dt.Columns["pk_column2"] };
So if you were making student_id your primary key, you could do this:
因此,如果您将 student_id 设为您的主键,您可以这样做:
dt.PrimaryKey = new DataColumn[] { dt.Columns["student_id"] };
回答by Nishank Jain
DataColumn pkCurrencyCodeId = TblCurrencyCode.Columns.Add("CurrencyCodeId", typeof(Int32));
TblCurrencyCode.PrimaryKey = new DataColumn[] { pkCurrencyCodeId };

