Search code examples
c#entity-frameworkentity-framework-6ef-code-firstentity-framework-migrations

Set identity to the previous created column during migration


I have a project with the CodeFirst database (Entity Framework 6) and two migration steps. Database is updated automatically by using this code in Application_Start in Global.asax:

Database.SetInitializer(
          new MigrateDatabaseToLatestVersion<MyDBEntities, MyNamespace.Configuration>());

First migration step is creating the tables:

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

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

Second migration step is adding identities to the created tables:

AlterColumn("dbo.GalleryAlbum", "Id", c => c.Int(nullable: false, identity: true));
AlterColumn("dbo.GalleryPics", "Id", c => c.Int(nullable: false, identity: true));

When I run the application, I can see that second migration code is running, information about two migrations is added to the _MigrationHistory table, but columns in both tables are not changed (without Identity). Here is the schema:

[Id]        INT             NOT NULL,
//other columns

Code First classes for the first migration are the following:

 public partial class GalleryAlbum
 {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
 }
 //GalleryPics is the same

and this one for the second migration step:

public partial class GalleryAlbum
 {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
 }
 //GalleryPics is the same

Could you please tell me, why Identity is not added to these columns and how I can fix it?

Thanks.

Update: Generated update requests to the database, which I got from the IDbCommandInterceptor:

ALTER TABLE [dbo].[GalleryAlbum] ALTER COLUMN [Id] [int] NOT NULL
ALTER TABLE [dbo].[GalleryPics] ALTER COLUMN [Id] [int] NOT NULL

Solution

  • 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);