2012-03-28 65 views
3

是否可以設置自動增量字段的值?如果使用主鍵5刪除記錄,但當前自動增量計數爲10,是否有任何方法可以重新插入該記錄,而其主鍵仍保持爲5(而不是11)?我正在嘗試在C#中使用Entity Framework 4.1來完成此操作。如何重新分配自動增加主鍵值?

回答

0

儘管這裏有幾個很好的建議,但我在處理這個問題的解決方案時意識到了幾件事情。數據庫是一個MySQL的披露可能會在這裏幫助,但我當時並沒有意識到這種差異會非常大。事實上,在MySql中,對於插入到自動增量主鍵中沒有鎖定。其結果是,此代碼插入與主鍵的記錄比自動增量指標的當前值少:

 var sql = @"INSERT INTO Work (
      WorkId , 
      LotId , 
      Description , 
      ) 
      VALUES (
      '5', '5', 'This Works' 
      );"; 
     using (var db = new Context()) 
     { 
      db.Database.ExecuteSqlCommand(sql); 
     } 

正確插入用5指標的記錄,即使當前自動增量計數爲11.

+0

有些人會想知道爲什麼如果這將是必要的。事實上,這種情況發生是罕見的,我的使用將是imp提供一個恢復功能,記錄可以用原始主鍵進行恢復。 – 2012-03-29 01:06:55

2

湯姆·黑格報價:

You could drop the primary key column and re-create it. All the ids will then be reassigned, I assume in the order in which the rows were inserted.

However, I'm not sure why you'd want to do this, especially if you have other tables that hold a foreign key to this table. If so you would need to update those fields as well, in which case dropping and recreating the column wouldn't be a good solution. You could instead re-name the column, remove the autoinc/primary key property, then create a new autoinc primary key column. You then would have both the old and new ids which you could use to update such foreign keys.

+0

我之前實際上已經閱讀過該人的答案,現在看來現在已經過時了。 – 2012-03-28 23:31:00

5

我想你也可以使用

Set Identity_Insert TableName ON 
Update your Id value 
Set Identity_Insert TableName OFF 
+0

這似乎是一個非常好的建議。我將不得不弄清楚如何在C#中運行這個原始SQL,然後如果它有效,我會將其標記爲答案。 – 2012-03-28 23:42:49

+0

我得到這個錯誤:'異常詳細信息:MySql.Data.MySqlClient.MySqlException:未知的系統變量'Identity_Insert'' – 2012-03-28 23:53:05

+0

@TravisJ你能發佈你正在使用的SQl命令嗎? – NiK 2012-03-28 23:56:47

1

您可以禁用identity specification。您的主鍵將保持不變,但您可以插入帶有您選擇的ID的新記錄。 插入記錄後,您想要重新啓用身份規範。