Search code examples
entity-frameworkentity-framework-coreasp.net-core-2.0npgsql

EF Core ValueGeneratedOnAdd does not work with postgresql


When using ConfigurationDbContext from Assembly IdentityServer4.EntityFramework.Storage

And seeding database with IdentityServer4.Models.Client entity enter image description here

I get the following error: PostgresException: 23502: null value in column "Id" violates not-null constraint

I took a look at the database and it turns out that the column is of type integer, even though I'd expect it to be serial. enter image description here

Below you can see parts of migration code responsible for column creation:

 migrationBuilder.CreateTable(
                name: "Clients",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),

and

modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

Basing on documentation https://www.npgsql.org/efcore/value-generation.html, calling ValueGeneratedOnAdd() on a integer column should result in serial type in the database.

Any thoughs on this?


Solution

  • Changing

    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
    

    to

    .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
    

    has solved the problem.