[英]Entity Framework 6 could not create a foreign key
我正在編寫一個使用EF 6遷移引擎來處理數據庫創建的應用程序。 使用CSharpMigrationCodeGenerator類,我在將由DbMigrator處理的遷移中構建了一個類庫程序集。 它工作正常,但使用外鍵出現此錯誤:
Exception Details: System.Data.Entity.Migrations.Infrastructure.MigrationsException: The Foreign Key on table 'dbo.Tabellina' with columns 'Tabella_Id' could not be created because the principal key columns could not be determined. Use the AddForeignKey fluent API to fully specify the Foreign Key.
遷移代碼是這樣的:
namespace AppMig.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class CreateTables: DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Tabella",
c => new
{
Id = c.Int(nullable: false, identity: true),
FromDate = c.DateTime(),
Todate = c.DateTime(),
campotabella = c.String(maxLength: 50),
})
.Index(t => t.FromDate, name: "tabella_fromdate_index")
.Index(t => t.Todate, name: "tabella_todate_index");
AddPrimaryKey("dbo.Tabella", "Id", name: "tabella_id_index");
CreateTable(
"dbo.Tabellina",
c => new
{
Id = c.Int(nullable: false, identity: true),
FromDate = c.DateTime(),
Todate = c.DateTime(),
campotabellina = c.String(maxLength: 50),
Tabella_Id = c.Int(nullable: false),
})
.ForeignKey("dbo.Tabella", t => t.Tabella_Id, cascadeDelete: true)
.Index(t => t.FromDate, name: "tabellina_fromdate_index")
.Index(t => t.Todate, name: "tabellina_todate_index")
.Index(t => t.Tabella_Id);
AddPrimaryKey("dbo.Tabellina", "Id", name: "tabellina_id_index");
}
public override void Down()
{
DropIndex("dbo.Tabellina", new[] { "Tabella_Id" });
DropForeignKey("dbo.Tabellina", "Tabella_Id", "dbo.Tabella");
DropIndex("dbo.Tabellina", "tabellina_todate_index");
DropIndex("dbo.Tabellina", "tabellina_fromdate_index");
DropPrimaryKey("dbo.Tabellina", name: "tabellina_id_index");
DropTable("dbo.Tabellina");
DropIndex("dbo.Tabella", "tabella_todate_index");
DropIndex("dbo.Tabella", "tabella_fromdate_index");
DropPrimaryKey("dbo.Tabella", name: "tabella_id_index");
DropTable("dbo.Tabella");
}
}
}
這是行不通的,但是,如果我創建僅添加外鍵的第二次遷移(當已經創建了兩個表時),則它可以工作。 由於應用程序的結構,對我來說創建第二個遷移真的很困難,因此我需要解決這個難題。
取自原始說明 ,是否有原因不能將.PrimaryKey(t => t.Id)用作主要CreateTable方法的一部分?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.