我有一個數據表,我必須分配一個主鍵,如果它還沒有。我嘗試過:如何檢查是否datatable.PrimaryKey設置
if (ds.Tables[0].PrimaryKey == null)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}
但PrimaryKey(在這種情況下)不爲null。當我檢查它包含:{System.Data.DataColumn [0]}我如何檢查?
我有一個數據表,我必須分配一個主鍵,如果它還沒有。我嘗試過:如何檢查是否datatable.PrimaryKey設置
if (ds.Tables[0].PrimaryKey == null)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}
但PrimaryKey(在這種情況下)不爲null。當我檢查它包含:{System.Data.DataColumn [0]}我如何檢查?
看起來它並不難,畢竟我已經嘗試過這一點,但顯然是做錯了什麼事,因爲當我再次嘗試它的工作:
DataColumn[] esl = new DataColumn[] { dt.Columns["Naam"] };
if (ds.Tables[0].PrimaryKey == null || ds.Tables[0].PrimaryKey == esl)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}
if (ds.Tables[0].PrimaryKey.Length == 0)
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
哈維爾的答案是正確的,但缺乏解釋。所以在這裏,DataTable.PrimaryKey屬性是DataColumns的集合。 如果DataTable的PrimaryKey屬性未設置爲集合的長度將爲0.如果DataTable將一個或多個字段定義爲主鍵,則PrimaryKey屬性的長度將反映此情況。 因此,檢查是這樣的:
if (ds.Tables[0].PrimaryKey.Length == 0)
會告訴我們,如果沒有添加列表示主鍵,以及部分
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
實際上添加的DataColumn(縣)所保持的列集合通過PrimaryKey屬性。
您好,請爲您的答案添加一些格式,以便更易讀。 – Chaithanya 2017-06-09 18:24:16
你的回答應該包含你的代碼的解釋和描述它是如何解決問題的。 – AbcAeffchen 2014-11-13 16:10:03