Cant remove identity attribute from PK

前端 未结 2 1543
故里飘歌
故里飘歌 2020-12-11 22:12

I need to change the data type of the primary key on one of my tables to string from int (I didn\'t say I WANT to...). The migration generates this bit of code:

<         


        
2条回答
  •  悲哀的现实
    2020-12-11 22:39

    At least for some versions of SQL Server, this can be done without dropping/recreating the database. It reportedly doesn't work for Azure (or didn't as of a 2015 comment). Inspired by this answer, here's my Up() method.

    Note that I don't have any foreign keys on this table so don't need to support that wrinkle covered in the linked answer

        public override void Up()
        {
            DropPrimaryKey("dbo.Products"); // Should be same as ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
            Sql("alter table dbo.Products add tempId int NOT NULL default -1");
            Sql("update dbo.Products set tempId = Id;");
            // Won't work. Can't remove identity: AlterColumn("dbo.Products", "Id", c => c.Int(nullable: false));
            Sql("alter table dbo.Products drop column Id");
            Sql("EXEC sp_rename 'Products.tempId', 'Id', 'COLUMN'");
            AddPrimaryKey("dbo.Products", "Id"); // Should be same as ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
        }
    

提交回复
热议问题