21

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?

2 Answers 2

32

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 } ); 
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your comments. However, there does not appear to be a property of table called TagValueID not one called Identifier.
I want this in Migration.Up() because I'm using migrations. If I put it in DbContext.OnModelCreating() then I don't get to use Migrations.
Mmmmh okay I removed this part of the answer, I'll be back to you in minutes with a solution I hope.
You were very close. I'm going to fix your answer and accept it.
Found the solution on my side a few seconds ago. Glad your problem was solved have a nice day.
13

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

3 Comments

PrimaryKey is under which name space? PrimaryKeyAttribute could not be found error is throwing even using System.ComponentModel.DataAnnotations and System.ComponentModel.DataAnnotations.Schema
@ZinMin, the only namespace I am using is Microsoft.EntityFrameworkCore. Again, Microsoft introduced the PrimaryKey attribute in EF Core 7.0 (learn.microsoft.com/en-us/ef/core/modeling/…)
@ZinMin Took me a moment time to find it, but you have to install the Microsoft.EntityFrameworkCore.Abstractions package to use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.