Set identity to the previous created column during migration

风格不统一 提交于 2019-12-06 12:27:40
eoghank

You can't ALTER a column to Identity in SQL Server, see Adding an identity to an existing column

Instead try add identity and column in one step:

CreateTable(
         "dbo.GalleryAlbum",
          c => new
          {
              Id = c.Int(nullable: false, identity:true),
              //other columns.....
          }).PrimaryKey(t => t.Id);

As per the accepted answer, if you can just include the identity when creating the table originally then that will solve the issue. If the table already exists however, and you have access to SSMS, then I find the easiest way is to:

  1. Back up the database...
  2. Change your class so has an identity in your code
  3. Generate the migration with the Package Manager Console (add-migration [your migration name] )
  4. Comment out the code in Up method in the newly generated migration
  5. Add a new line of code ready to receive the SQL you'll generate below: Sql (@" ");
  6. Go into SSMS and make sure it's set to generate scripts when you make a table change
  7. Add the identity in the table designer in SMSS
  8. Save the table change in SSMS and copy the SQL generated. (That SQL makes a copy of the table with the data, drops the original table, then recreates the original table with the identity set on the column, then copies all the data back and adds all the foreign keys and constraints back on again)
  9. Paste the SQL you just copied between the speech marks in the code you added above.
  10. Run the migration

That should then give you a migration that adds the identity and can be run on other copies of the database successfully.

NB:The Down method that was generated won't work either because it will be removing the identity, which EF also can't do. If you need the Down method to work create a copy of the SQL you added and adjust it to create the table without the identity again.

ALTER TABLE [Mytable] add constraint [PK_dbo.Mytable] primary key (Id) works for me if Id was there and had data in place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!