简体   繁体   中英

Entity Framework Primary Key column not auto incrementing

I currently have a problem where the primary key in my ShoppingBasket table is not auto incrementing every time I do db.SaveChanges which results in a duplicate key error. I was under the impression that any primary key in an Entity Framework DB was already set to auto increment but maybe I am wrong?

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])
);

I have tried some suggestions such as assinging the CartID key in the code as CartID = -1 and also adding [DatabaseGenerated] and [Key] in the ShoppingBasket model but I still have the same error.

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; }
}

I have no errors when inserting a unique key manually so I think the issue is finding a solution to make the CartID auto increment.

Primary key is not incrementing by default. You should add also IDENTITY(1, 1) . The code would therefore look like following:

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])
);

I think that Identity field should be bigint.

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])
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM