gpt4 book ai didi

c# - 使用 Entity Framework 自动递增主键

转载 作者:行者123 更新时间:2023-12-02 19:35:20 24 4
gpt4 key购买 nike

我有一个表,我想在不指定 UserID 的情况下向其中插入项目。我希望自动生成此 ID。

CREATE TABLE [dbo].[UserMaster] 
(
[UserID] INT NOT NULL ,
[UserName] VARCHAR (50) NULL,
[UserPassword] VARCHAR (50) NULL,
[UserRoles] VARCHAR (500) NULL,
[UserEmailID] VARCHAR (100) NULL,

PRIMARY KEY CLUSTERED ([UserID] ASC)
);

这里我尝试通过 C# 插入行:

using (LessonesDBEntities context = new LessonesDBEntities())
{
var u = new UserMaster//Make sure you have a table called UserMaster in DB
{
UserName = "test username",
UserPassword = "test password",
UserEmailID = "test email",
UserRoles = "User"
};

context.UserMaster.Add(u);
context.SaveChanges();
}

但我得到异常:

Violation of PRIMARY KEY constraint 'PK__tmp_ms_x__1788CCACDB8355D2'. Cannot insert duplicate key in object 'dbo.UserMaster'. The duplicate key value is (0). The statement has been terminated.

最佳答案

[DatabaseGenerated(DatabaseGeneratedOption.Identity)] 属性添加到您的身份字段 UserId

public class UserMaster
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }

public string UserEmailID { get; set; }
public string UserRoles { get; set; }
}

当您基于该模型创建迁移和表时,EF 会创建具有自动增量的标识字段。

关于c# - 使用 Entity Framework 自动递增主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61119828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com