实体框架 6 无法创建外键
本文关键字:创建 框架 实体 | 更新日期: 2023-09-27 18:30:54
我正在编写一个使用 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 方法的一部分?