Asp.net-Core

如何使用 EFCore Code First 遷移指定複合主鍵

  • November 11, 2020

我正在使用帶有 Code First 和遷移的 Asp.Net Core 2.1、Mvc、c#、EF Core。

我正在嘗試在方法中建構一個具有復合主鍵的表Migration.Up()

migrationBuilder.CreateTable(
   name: "TagValueAttributes",
   columns: table => new {
       TagValueID = table.Column<Int64>(nullable: false),
       Identifier = table.Column<string>(nullable: false, unicode: true, maxLength: 256),
       Value = table.Column<string>(nullable: true, unicode: true, maxLength: 2048)
   },
   constraints: table => {
       table.PrimaryKey(
           name: "PK_TagValueAttributes",
           columns: // what goes here???
       )
   }
);

我不知道為呼叫的columns參數指定什麼constraints table.PrimaryKey()。我想要 columns TagValueID,並Identifier形成複合鍵。

我需要為columns參數指定什麼?

為什麼要將它放在Migration.Up()方法中?

您可以DbContext通過覆蓋OnModelCreating()方法中的 Fluent API 執行此操作:

protected override void OnModelCreating(ModelBuilder builder)
{
   builder.Entity<TagValueAttributes>().HasKey(t => new { t.TagValueID, t.Identifier });
}

如果您想保留它,Migration.Up()請執行以下操作:

table.PrimaryKey(
   name: "PK_TagValueAttributes",
   columns: t => new { t.Identifier, t.TagValueID }
);

引用自:https://stackoverflow.com/questions/51993903