Auto-increment on partial primary key with Entity Framework Core

Martin picture Martin · Mar 22, 2016 · Viewed 104.1k times · Source

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

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

Both fields are marked as the primary key when I create the database in PostgreSQL but the Id field is not marked as auto increment. I have also tried to add

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

to the Id field under Foo without it making any difference on the migration code. Is there a way to make the Id AI although it is a PPK?

Answer

octavioccl picture octavioccl · Mar 22, 2016

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.