简体   繁体   中英

Why is the generated Code First Migration broken for Update-Database in this instance?

I renamed one of my entities from UploadedFile to File and executed an Add-Migration , which resulted in the following;

    public override void Up()
    {
        RenameTable(name: "dbo.UploadedFiles", newName: "Files");
        DropPrimaryKey("dbo.UploadedFiles");
        AddColumn("dbo.Files", "FileId", c => c.Int(nullable: false, identity: true));
        AddPrimaryKey("dbo.Files", "FileId");
        DropColumn("dbo.Files", "UploadedFileId");
    }

After which I executed an Update-Database and found that the migration would fail. I had to re-order two of the statements to make it work;

  1. DropPrimaryKey needed to be prior to RenameTable because the generated code referenced the old table name
  2. DropColumn needed to be executed prior to AddColumn otherwise a multiple identity column error was thrown.

The result was this, which worked as expected;

        DropPrimaryKey("dbo.UploadedFiles");
        RenameTable(name: "dbo.UploadedFiles", newName: "Files");
        DropColumn("dbo.Files", "UploadedFileId");
        AddColumn("dbo.Files", "FileId", c => c.Int(nullable: false, identity: true));
        AddPrimaryKey("dbo.Files", "FileId");

Is it expected that I'll need to hand-edit these generated migrations, or have I done something wrong that is affecting generation?

Is changing the table name and the primary key too much in one go, and should I instead be executing an Add-Migration at each step?

This sounds like a bug, and I'd recommend you create an issue on codeplex . It appears that EF can't determine which statement has higher priority when creating the migration.

Of course, if you used the convention of simply naming the PK Id on a table, you'd avoid this issue altogether. I typically find this to be more readable as it prevents PKs from blending in with FKs (eg Id and OwnerId vs FileId and OwnerId )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM