实体框架主键列不自动递增

时间:2014-04-07 16:46:02

标签: c# sql entity-framework

我目前遇到的问题是,每次执行db.SaveChanges时,ShoppingBasket表中的主键都不会自动递增,从而导致重复键错误。我的印象是,实体框架数据库中的任何主键已经设置为自动增量,但也许我错了?

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

我尝试了一些建议,比如将代码中的CartID键分配为CartID = -1,并在ShoppingBasket模型中添加[DatabaseGenerated]和[Key],但我仍然有同样的错误。

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自动增加的解决方案。

2 个答案:

答案 0 :(得分: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])
);

答案 1 :(得分:1)

我认为Identity字段应该是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])
);