简体   繁体   English

使用实体框架自动增加主键

[英]Auto increment primary key with Entity Framework

I have a table and I want to insert items into it without specifying the UserID .我有一个表,我想在不指定UserID的情况下将项目插入其中。 I want this ID to be generated automatically.我希望自动生成此 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)
);

Here I try to insert row via C#:在这里,我尝试通过 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();
}

But I get exception:但我得到例外:

Violation of PRIMARY KEY constraint 'PK__tmp_ms_x__1788CCACDB8355D2'.违反主键约束“PK__tmp_ms_x__1788CCACDB8355D2”。 Cannot insert duplicate key in object 'dbo.UserMaster'.无法在 object 'dbo.UserMaster' 中插入重复密钥。 The duplicate key value is (0).重复键值为 (0)。 The statement has been terminated.该语句已终止。

To Make auto-increment at Database level you should include IDENTITY in the DDL: UserID int identity(1,1) not null要在数据库级别进行自动增量,您应该在 DDL 中包含IDENTITYUserID int identity(1,1) not null

(1,1) stands for UserID will start at 1 and increment by 1 for each INSERT . (1,1)代表UserID将从1开始,并为每个INSERT递增 1。

Add [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute to your identity field UserId .[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; }
}

When your create migration and table based on that model, EF creates identity field with auto increment.当您基于该 model 创建迁移和表时,EF 创建具有自动增量的标识字段。

Entity Framework doesn't know your whole database, it only knows the records you've already fetched into its context. Entity Framework 不知道你的整个数据库,它只知道你已经提取到它的上下文中的记录。 Therefore it cannot determine the maximum used id in the given table.因此它无法确定给定表中使用的最大 id。

You have 3 options here:您在这里有 3 个选项:

Use a feature of your db to automatically set the id, an auto-incremented identity column使用你的数据库的一个特性来自动设置 id,一个自动递增的标识列

or或者

Write a function in your db that returns the max id and set it yourself in EF在您的数据库中编写一个 function 返回最大 id 并在 EF 中自行设置

or或者

Get the whole table in your EF (load it completely) and then select the max id.在您的 EF 中获取整个表(完全加载),然后 select 获取最大 ID。

I strongly advise against option 2 and 3 and for option 1 to use a auto-increment-feature of your database.我强烈建议不要使用选项 2 和 3,建议选项 1 使用数据库的自动增量功能。 You should insert them via EF with a id of null and the DB will set the id.您应该通过 EF 插入它们,id 为null ,DB 将设置 id。 You need to mark the column accordingly.您需要相应地标记该列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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