Auto-increment on partial primary key with Entity Framework Core

后端 未结 5 2054
野趣味
野趣味 2020-12-13 05:50

I have declared the following model using the EF Core fluent API:

modelBuilder.Entity()
    .HasKey(p => new { p.Name, p.Id });
5条回答
  •  旧巷少年郎
    2020-12-13 06:32

    To anyone who came across this question who are using SQL Server Database and still having an exception thrown even after adding the following annotation on the int primary key

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

    Please check your SQL, make sure your the primary key has 'IDENTITY(startValue, increment)' next to it,

    CREATE TABLE [dbo].[User]
    (
        [Id] INT IDENTITY(1,1) NOT NULL PRIMARY KEY
    )
    

    This will make the database increments the id every time a new row is added, with a starting value of 1 and increments of 1.

    I accidentally overlooked that in my SQL which cost me an hour of my life, so hopefully this helps someone!!!

提交回复
热议问题