我正在使用 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
参数指定什么?
为什么要把这个放在
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 }
);
使用
EF Core 7.0
你可以使用数据注释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; }
}