[c#] 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?

The answer is


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.


Annotate the property like below

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

To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():

builder.ForNpgsqlUseIdentityColumns();

This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().

postgres efcore value generation


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


Specifying the column type as serial for PostgreSQL to generate the id.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to postgresql

Subtracting 1 day from a timestamp date pgadmin4 : postgresql application server could not be contacted. Psql could not connect to server: No such file or directory, 5432 error? How to persist data in a dockerized postgres database using volumes input file appears to be a text format dump. Please use psql Postgres: check if array field contains value? Add timestamp column with default NOW() for new rows only Can't connect to Postgresql on port 5432 How to insert current datetime in postgresql insert query Connecting to Postgresql in a docker container from outside

Examples related to entity-framework-core

dotnet ef not found in .NET Core 3 How to update record using Entity Framework Core? Unable to create migrations after upgrading to ASP.NET Core 2.0 Error: the entity type requires a primary key Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver' auto create database in Entity Framework Core Entity Framework Core add unique constraint code-first How to unapply a migration in ASP.NET Core with EF Core The term "Add-Migration" is not recognized Auto-increment on partial primary key with Entity Framework Core