如何使用 EFCore Code First Migrations 指定复合主键

Sam*_*Axe 11 composite-primary-key asp.net-core asp.net-core-2.1 ef-core-2.1 entity-framework-migrations

我正在使用 Asp.Net Core 2.1、Mvc、c#、EF Core with Code First 和 Migrations。

我正在尝试构建一个在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???
        )
    }
);
Run Code Online (Sandbox Code Playgroud)

我不知道为调用的columns参数指定什么constraints table.PrimaryKey()。我想要 columns TagValueID,并Identifier形成复合键。

我需要为columns参数指定什么?

Sel*_*mir 18

你为什么要把它放在Migration.Up()方法中?

您可以DbContext通过覆盖OnModelCreating()方法中的 Fluent API 执行此操作:

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

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

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


Mar*_*ich 11

使用EF Core 7.0您可以使用数据注释
https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs=data-annotations

using Microsoft.EntityFrameworkCore;

[PrimaryKey(nameof(Identifier), nameof(TagValueID))]
internal class table
{
    public Int64 Identifier { get; set; }
    public string TagValueID { get; set; }
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)