简体   繁体   English

Ef core code first Error: Key ("Id")=(33) already exists

[英]Ef core code first Error : Key ("Id")=(33) already exists

I am doing a crud for Destinations table in a asp.net core project.我正在为 asp.net 核心项目中的Destinations表做一个 crud。 ( using ef core code first method ) (使用ef核心代码第一方法)

when create a new Destinations I got error in debug console like this.当创建一个新的目的地时,我在调试控制台中遇到了这样的错误。

Exception data:
    MessageText: duplicate key value violates unique constraint "PK_Destinations"
    Detail: Key ("Id")=(33) already exists.
    SchemaName: public
    TableName: Destinations
    ConstraintName: PK_Destinations

For some reasons We have already create a Destinations table and added data manually.由于某些原因,我们已经创建了一个 Destinations 表并手动添加了数据。 And now doing a crud for that table .现在为那张桌子做点菜 I guess that's why this error Key ("Id")=(33) already exists.我想这就是为什么这个错误Key ("Id")=(33) already exists. occurs.发生。

DbContext.cs数据库上下文.cs

public DbSet<Destination> Destinations { get; set; }

service.Cs服务.cs

  public async Task<Destination> Create(Destination destination)
        {
            await _catalogDbContext.Destinations.AddAsync(destination);
            await _catalogDbContext.SaveChangesAsync();
            return destination;
        }

My Question is我的问题是

  • I have 100 rows in my table.我的表中有 100 行。 We can not remove them.我们不能删除它们。 So destination id should start from 301 when adding new destination.因此,添加新目的地时,目的地 ID 应从 301 开始。

  • Our development Database has 200 rows in our table.我们的开发数据库在我们的表中有 200 行。 We can not remove them.我们不能删除它们。 So destination id should start from 201 when adding new destination.因此,添加新目的地时,目的地 ID 应从 201 开始。

  • Our production Database has 240 rows in our table.我们的生产数据库在我们的表中有 240 行。 We can not remove them.我们不能删除它们。 So destination id should start from 241 when adding new destination.因此,添加新目的地时,目的地 id 应从 241 开始。

How can I do, when create a destination Id should starting from 101, 201 or 241. And The id should increase automatically after a new one is added.?当创建一个目标 ID 应该从 101、201 或 241 开始时,我该怎么办。并且在添加新的 ID 后应该自动增加。?

Edit: Destination.cs编辑:Destination.cs

public class Destination
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; private set; }

        [Required]
        public string Continent { get; set; }

        [Required]
        public string Country { get; set; }

        [Required]
        public string Iso { get; set; }

        [Required]
        public string Name { get; set; }
}

it seems that key id =33 already exist in table and you cannot add duplicate as its primary key.似乎键 id =33 已经存在于表中,您不能添加重复项作为其主键。

you can set identity value for Id column using DBCC command您可以使用 DBCC 命令为 Id 列设置标识值

  1. check current seed: DBCC CHECKIDENT ('yourtablename');检查当前种子:DBCC CHECKIDENT ('yourtablename');
  2. set new seed;种下新的种子; DBCC CHECKIDENT ('yourtablename', RESEED, 200); DBCC CHECKIDENT ('yourtablename', RESEED, 200);

then run your code.然后运行你的代码。

When you add a new entity, it's better to let Id value as default value, don't try to assign it.添加新实体时,最好让Id值作为默认值,不要尝试分配它。 (For example, Id is int so let the value = 0) (例如,Id 是int所以让值 = 0)

public async Task<Destination> Create()
{
     var destination = new Destination
     {
        Continent = "What ever",
        Country = "...."
        // Init all required properties BUT Id
     };

     // At this line, destination.Id == 0 because you didn't assign a value
     await _catalogDbContext.Destinations.AddAsync(destination);
     await _catalogDbContext.SaveChangesAsync();

     // At this line, you should see destination.Id > 0, the value is assigned by EntityFramework
     return destination;
}

There is no issue with code snippet you have mentioned here.您在此处提到的代码片段没有问题。 need to work on database side.需要在数据库端工作。

what i understood is, your table having pk column id which is identity ie auto increment.我的理解是,您的表具有 pk 列 id,即标识,即自动递增。 in such case you need to reseed it.在这种情况下,您需要重新播种。 for ex.例如。 if your table having existing records then you need to get max value of id column;如果您的表有现有记录,那么您需要获取 id 列的最大值; let say id column max value is 200. now you have to tell database to set the identity to 200. next time, when new record inserted it will be stored with id=201 and so on.假设 id 列的最大值为 200。现在您必须告诉数据库将标识设置为 200。下一次,当插入新记录时,它将以 id=201 存储,依此类推。

step to reseed table identity value is as below重新设置表标识值的步骤如下

DBCC CHECKIDENT ('yourtablename', RESEED, 200)

https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql?view=sql-server-ver15 https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql?view=sql-server-ver15

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

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