实体框架6无法创建外键

时间:2014-11-18 13:32:29

标签: c# entity-framework foreign-keys database-migration

我正在编写一个使用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");
        }
    }
}

这不起作用但是,如果我创建第二个只添加外键的迁移(当两个表已经创建时),它就可以工作。由于应用程序结构,我真的很难创建第二个迁移,所以我需要解决这个谜。

1 个答案:

答案 0 :(得分:0)

取自vanilla instructions,是否有理由不使用.PrimaryKey(t => t.Id)作为主要CreateTable方法的一部分?