Cant remove identity attribute from PK

前端 未结 2 1544
故里飘歌
故里飘歌 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:31

    Removing an identity specification from a column can only be done by re-creating the table. Look at the ALTER TABLE - ALTER COLUMN statement: there is no syntax to change (add or remove) an identity specification.

    So I'm afraid you'll have to do this manually and make a fresh start for subsequent migrations.

    BTW Sql Server Management Studio won't help you doing this. You may want to use Toad for Sql Server. It creates a full table rebuild script when you remove an identity specification.

    0 讨论(0)
  • 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)
        }
    
    0 讨论(0)
提交回复
热议问题