[英]Ef core code first Error : Key ("Id")=(33) already exists
我正在為 asp.net 核心項目中的Destinations
表做一個 crud。 (使用ef核心代碼第一方法)
當創建一個新的目的地時,我在調試控制台中遇到了這樣的錯誤。
Exception data:
MessageText: duplicate key value violates unique constraint "PK_Destinations"
Detail: Key ("Id")=(33) already exists.
SchemaName: public
TableName: Destinations
ConstraintName: PK_Destinations
由於某些原因,我們已經創建了一個 Destinations 表並手動添加了數據。 現在為那張桌子做點菜。 我想這就是為什么這個錯誤Key ("Id")=(33) already exists.
發生。
數據庫上下文.cs
public DbSet<Destination> Destinations { get; set; }
服務.cs
public async Task<Destination> Create(Destination destination)
{
await _catalogDbContext.Destinations.AddAsync(destination);
await _catalogDbContext.SaveChangesAsync();
return destination;
}
我的問題是
我的表中有 100 行。 我們不能刪除它們。 因此,添加新目的地時,目的地 ID 應從 301 開始。
我們的開發數據庫在我們的表中有 200 行。 我們不能刪除它們。 因此,添加新目的地時,目的地 ID 應從 201 開始。
我們的生產數據庫在我們的表中有 240 行。 我們不能刪除它們。 因此,添加新目的地時,目的地 id 應從 241 開始。
當創建一個目標 ID 應該從 101、201 或 241 開始時,我該怎么辦。並且在添加新的 ID 后應該自動增加。?
編輯:Destination.cs
public class Destination
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; private set; }
[Required]
public string Continent { get; set; }
[Required]
public string Country { get; set; }
[Required]
public string Iso { get; set; }
[Required]
public string Name { get; set; }
}
似乎鍵 id =33 已經存在於表中,您不能添加重復項作為其主鍵。
您可以使用 DBCC 命令為 Id 列設置標識值
然后運行你的代碼。
添加新實體時,最好讓Id
值作為默認值,不要嘗試分配它。 (例如,Id 是int
所以讓值 = 0)
public async Task<Destination> Create()
{
var destination = new Destination
{
Continent = "What ever",
Country = "...."
// Init all required properties BUT Id
};
// At this line, destination.Id == 0 because you didn't assign a value
await _catalogDbContext.Destinations.AddAsync(destination);
await _catalogDbContext.SaveChangesAsync();
// At this line, you should see destination.Id > 0, the value is assigned by EntityFramework
return destination;
}
您在此處提到的代碼片段沒有問題。 需要在數據庫端工作。
我的理解是,您的表具有 pk 列 id,即標識,即自動遞增。 在這種情況下,您需要重新播種。 例如。 如果您的表有現有記錄,那么您需要獲取 id 列的最大值; 假設 id 列的最大值為 200。現在您必須告訴數據庫將標識設置為 200。下一次,當插入新記錄時,它將以 id=201 存儲,依此類推。
重新設置表標識值的步驟如下
DBCC CHECKIDENT ('yourtablename', RESEED, 200)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.