dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.8k stars 3.19k forks source link

Loss autoincrement after change PK type #21839

Closed ASBrattsev closed 2 years ago

ASBrattsev commented 4 years ago

After creating a migration with a change in the primary key type from int to long, autogeneration is lost.

Steps to reproduce

I created a model:

public class TestClass
    {
        public int Id { get; set; }

        public string Description { get; set; }
    }

and generate migration:

protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "TestClass",
                schema: "test",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
                    Description = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_TestClass", x => x.Id);
                });
        }

after, I change type of PK

public class TestClass
    {
        public long Id { get; set; }

        public string Description { get; set; }
    }

and generate new migration:

protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AlterColumn<long>(
                name: "Id",
                schema: "test",
                table: "TestClass",
                nullable: false,
                oldClrType: typeof(int))
                .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
                .OldAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn);
        }

after migrate data base I loss defalt value for PK image

Further technical details

EF Core version: 2.1.1 Database provider: Npgsql.EntityFrameworkCore.PostgreSQL Target framework: NET Core 2.2 Operating system: Windows 10 Pro IDE: JetBrains Rider 2020.1.4

ajcvickers commented 4 years ago

Ping @roji

roji commented 4 years ago

Sorry for taking long to answer.

This has already been resolved in EF Core 3.1 when using the old serial columns. It also does not occur when using the new (default) identity columns. I suggest you take a look at moving to 3.1.

PS The problem above is specific to the Npgsql provider, and so belongs in github.com/npgsql/efcore.pg rather than here (I know it's sometimes tricky to know where the problem is, just saying).