Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-increment on partial primary key with Entity Framework Core

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?

like image 997
Martin Avatar asked Mar 22 '16 13:03

Martin


People also ask

Can a primary key be auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Can I auto increment a column that is not a primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.

How can change primary key to auto increment in SQL Server?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.

What is ValueGeneratedNever?

The Entity Framework Core Fluent API ValueGeneratedNever provides a way to specify that the value for the selected property should never be generated automtically by the database. This is useful if you want to circumvent the database's default behaviour.


1 Answers

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.

like image 154
octavioccl Avatar answered Sep 28 '22 06:09

octavioccl