Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF5:could not be created because the principal key columns could not be determined. Use the AddForeignKey fluent API to fully specify the Foreign Key

We are using Entity Frame Work 5.0. and database MySQL. When we are try to migrate time get an exception.

could not be created because the principal key columns could not be determined. Use the AddForeignKey fluent API to fully specify the Foreign Key.

like image 675
user2017909 Avatar asked Mar 15 '13 11:03

user2017909


2 Answers

As explained here http://www.ozkary.com/2015/02/the-foreign-key-on-table-with-columns.html, you can have the issue when putting a FK to a table that is not part of your Db Context

So instead of doing

CreateTable(
    "dbo.App",
    c => new
    {
        Id = c.Int(nullable: false, identity: true),
        Name = c.String(nullable: false, maxLength: 150),
        RoleId = c.String()
    })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.MyRoles", t => t.RoleId)
    .Index(t => t.RoleId);

you should do:

CreateTable(
    "dbo.App",
    c => new
    {
        Id = c.Int(nullable: false, identity: true),
        Name = c.String(nullable: false, maxLength: 150),
        RoleId = c.String()
    })
    .PrimaryKey(t => t.Id)
    .Index(t => t.RoleId);

AddForeignKey("dbo.App", "RoleId", "dbo.Roles","Id");
like image 192
Bart Jolling Avatar answered Nov 12 '22 18:11

Bart Jolling


Entity framework demands that relation is built between whole primary key in the principal table and corresponding columns (foreign key) it the dependent table.

Check if all your tables contain PRIMARY KEY COLUMN

like image 25
Vitthal Avatar answered Nov 12 '22 18:11

Vitthal