簡體   English   中英

如何使用 EF Core 將單個主鍵更改為復合主鍵

[英]How to change single primary key to composite primary key with EF Core

我想刪除已創建且不包含數據的 SQL 表中的單個主鍵 Id 列,並改為定義復合主鍵。

我當前的實體定義如下:

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

public long IpFrom { get; set; }

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

我想更新到這個:

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

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

我已經使用 fluent api 進行了以下定義:

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

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

然后我使用 EF Tool 創建遷移文件並得到以下遷移文件。

    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");
    }
}

當我想使用 EF 工具更新數據庫時,我收到以下錯誤,即使一切對我來說都是正確的:

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

謝謝你的幫助。

我試過這個,運行dotnet ef database update不會應用遷移。

相反,從遷移生成 SQL 文件並執行 SQL 查詢。 嘗試這樣做。

cd ToYourDbModelProject
dotnet ef  --startup-project ../PathToStartupProject/ migrations script previous_migration current_migration -o current_migration.sql --context Namespace.To.Your.DbContext

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM