Auto-increment on partial primary key with Entity Framework Core Auto-increment on partial primary key with Entity Framework Core asp.net asp.net

Auto-increment on partial primary key with Entity Framework Core


Well those Data Annotations should do the trick, maybe is something related with the PostgreSQL Provider.

From EF Core documentation:

Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during SaveChanges.

You could also try with this Fluent Api configuration:

modelBuilder.Entity<Foo>()            .Property(f => f.Id)            .ValueGeneratedOnAdd();

But as I said earlier, I think this is something related with the DB provider. Try to add a new row to your DB and check later if was generated a value to the Id column.


First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()            .HasKey(p => new { p.Name, p.Id });modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo{    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]    [Key, Column(Order = 0)]    public int Id { get; set; }    [Key, Column(Order = 1)]    public string Name{ get; set; }}


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!!!