2014-04-07 89 views
2

我目前有一個問題,其中我的ShoppingBasket表中的主鍵不會自動遞增每次我做db.SaveChanges這會導致重複鍵錯誤。我的印象是實體框架數據庫中的任何主鍵已經設置爲自動遞增,但也許我錯了?實體框架主鍵列不自動遞增

ShoppingBasket.db

CREATE TABLE [dbo].[ShoppingBasket] (
[CartID]   INT   NOT NULL, 
[BasketID]  VARCHAR (50) NULL, 
[BasketQuantity] INT   NOT NULL, 
[ProductID]  INT   NOT NULL, 
PRIMARY KEY CLUSTERED ([CartID] ASC), 
CONSTRAINT [FK_ShoppingBasket_Products] FOREIGN KEY ([ProductID]) REFERENCES [dbo].[Products] ([ProductID]) 
); 

我已經嘗試了一些建議,如assinging在代碼中CartID鍵CartID = -1,也仍然在增加[DatabaseGenerated],並在ShoppingBasket模型[關鍵],但我有同樣的錯誤。

ShoppingBasket.Model

public partial class ShoppingBasket 
{ 

    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int CartID { get; set; } 
    public string BasketID { get; set; } 
    public int BasketQuantity { get; set; } 
    public int ProductID { get; set; } 

    public virtual Product Product { get; set; } 
} 

我插入唯一鍵時沒有錯誤,手工,所以我認爲這個問題是找到一個解決方案,使CartID自動遞增。

回答

4

默認情況下主鍵不增量。您還應該添加IDENTITY(1, 1)。代碼因此將如下所示:

CREATE TABLE [dbo].[ShoppingBasket] (
    [CartID]   INT   NOT NULL IDENTITY(1,1), 
    [BasketID]  VARCHAR (50) NULL, 
    [BasketQuantity] INT   NOT NULL, 
    [ProductID]  INT   NOT NULL, 
    PRIMARY KEY CLUSTERED ([CartID] ASC), 
    CONSTRAINT [FK_ShoppingBasket_Products] FOREIGN KEY ([ProductID]) REFERENCES [dbo].[Products] ([ProductID]) 
); 
+0

感謝您的澄清,也固定我的問題! – DanBarber

1

我認爲Identity字段應該是bigint。佛更多詳情,請訪問 - http://www.sqlteachers.com/entries/2021-Using-Identity-in-SQL-Server

CREATE TABLE [dbo].[ShoppingBasket] ( [CartID] BIGINT NOT NULL IDENTITY(1,1), [BasketID] VARCHAR (50) NULL, [BasketQuantity] INT NOT NULL, [ProductID] INT NOT NULL, PRIMARY KEY CLUSTERED ([CartID] ASC), CONSTRAINT [FK_ShoppingBasket_Products] FOREIGN KEY ([ProductID]) REFERENCES [dbo].[Products] ([ProductID]) );