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

问题描述 投票:0回答:2

我正在使用 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()
参数指定什么。我想要列
TagValueID
Identifier
来形成复合键。

我需要为

columns
参数指定什么?

asp.net-core entity-framework-migrations composite-primary-key asp.net-core-2.1 ef-core-2.1
2个回答
26
投票

为什么要把这个放在

Migration.Up()
方法里?

您可以通过

DbContext
中的 Fluent API 重写
OnModelCreating()
方法来执行此操作:

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

3
投票

使用

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.