Reputation: 33738
I'm using Asp.Net Core 2.1, Mvc, c#, EF Core with Code First and Migrations.
I'm trying to build a table that has a composite primary key in the Migration.Up()
method:
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???
)
}
);
I don't know what to specify for the columns
parameter of the constraints
table.PrimaryKey()
call. I would like columns TagValueID
, and Identifier
to form the composite key.
What do I need to specify for the columns
parameter?
Upvotes: 19
Views: 26330
Reputation: 626
Using EF Core 7.0
you can use data annotations
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; }
}
Upvotes: 13
Reputation: 1206
Why do you want to put this in the Migration.Up()
method ?
You can do this via the Fluent API in your DbContext
by overriding OnModelCreating()
method :
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TagValueAttributes>().HasKey(t => new { t.TagValueID, t.Identifier });
}
If you want tho keep this in Migration.Up()
then do:
table.PrimaryKey(
name: "PK_TagValueAttributes",
columns: t => new { t.Identifier, t.TagValueID }
);
Upvotes: 31