Asp.net-Core
如何使用 EFCore Code First 遷移指定複合主鍵
我正在使用帶有 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參數指定什麼constraintstable.PrimaryKey()。我想要 columnsTagValueID,並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 } );