Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 460
Sam Axe Avatar asked Aug 23 '18 20:08

Sam Axe


1 Answers

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 }
);
like image 65
Selmir Avatar answered Oct 06 '22 08:10

Selmir