How to change single primary key to composite primary key with EF Core

.net .net-core c# entity-framework entity-framework-core

Question

I want to delete the single primary key Id column in a SQL table that has already been created and does not contain data and define a composite primary key instead.

My current entity definition is as follows:

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

public long IpFrom { get; set; }

public long IpTo { get; set; }
...

And I want to update to this:

[Key, Column(Order = 0)]
public long IpFrom { get; set; }

[Key, Column(Order = 1)]
public long IpTo { get; set; }
...

I have already made the following definition using fluent api:

protected override void OnModelCreating(ModelBuilder builder)
{
   base.OnModelCreating(builder);

   builder.Entity<IPv4LocationEntity>()
     .HasKey(b => new {b.IpFrom, b.IpTo})
     .HasName("PK_TableName");
}

Then I used EF Tool to create migration files and got the following migration file.

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropPrimaryKey(
            name: "PK_TableName",
            table: "TableName");

        migrationBuilder.DropColumn(
            name: "Id",
            table: "TableName");

        migrationBuilder.AddPrimaryKey(
            name: "PK_TableName",
            table: "TableName",
            columns: new[] { "IpFrom", "IpTo" });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropPrimaryKey(
            name: "PK_TableName",
            table: "TableName");

        migrationBuilder.AddColumn<int>(
            name: "Id",
            table: "TableName",
            type: "int",
            nullable: false,
            defaultValue: 0)
            .Annotation("SqlServer:Identity", "1, 1");

        migrationBuilder.AddPrimaryKey(
            name: "PK_TableName",
            table: "TableName",
            column: "Id");
    }
}

I get the following error when I want to update the database with the EF tool even though everything seems right to me:

ALTER TABLE DROP COLUMN failed because column 'Id' does not exist in table 'TableName'.

Thanks for your help.

1
1
3/25/2020 7:58:58 AM

Accepted Answer

I tried this and running dotnet ef database update does not apply the migration.

Instead, generated SQL file from the migration and execute the SQL queries. Try doing this.

cd ToYourDbModelProject
dotnet ef  --startup-project ../PathToStartupProject/ migrations script previous_migration current_migration -o current_migration.sql --context Namespace.To.Your.DbContext
1
3/25/2020 8:27:17 AM


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