EF Core ValueGeneratedOnAdd does not work with postgresql

asp.net-core-2.0 entity-framework entity-framework-core npgsql

Question

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?

1
1
12/2/2018 11:08:48 PM

Accepted Answer

Changing

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

to

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

has solved the problem.

4
12/3/2018 1:26:39 PM

Popular Answer

Extension method for common providers.

public static void HasIdentityAnnotation<T>(PropertyBuilder<T> builder)
{
    builder.HasAnnotation("Sqlite:Autoincrement", true)
        .HasAnnotation("MySql:ValueGeneratedOnAdd", true)
        .HasAnnotation("Npgsql:ValueGenerationStrategy", 
Npgsql.EntityFrameworkCore.PostgreSQL.Metadata.NpgsqlValueGenerationStrategy.SerialColumn)
        .HasAnnotation("SqlServer:ValueGenerationStrategy", Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.IdentityColumn);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow