How to specify a composite primary key using EFCore Code First Migrations

Sam Axe picture Sam Axe · Aug 23, 2018 · Viewed 8.5k times · Source

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?

Answer

Selmir picture Selmir · Aug 23, 2018

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