[英]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.