Migrating EF: Error changing indexed field to NULL
The code in my initial migration was as follows.
CreateTable( "dbo.Sites", c => new { Id = c.Int(nullable: false, identity: true), Description = c.String(maxLength: 450) }) .PrimaryKey(t => t.Id); To make the Description field unique, I added the following to the end of the UP method
CreateIndex ("dbo.Sites", "Description", unique: true);
Later, I decided to make the Description field mandatory.
New migration generates next change
AlterColumn ("dbo.Sites", "Description", c => c.String (nullable: false, maxLength: 450));
However, when this change tries to start, I get an error
ALTER TABLE ALTER COLUMN Description failed because one or more objects are accessing this column.
I was able to isolate the SQL string using the profiler since
ALTER TABLE [dbo]. [Sites] ALTER COLUMN [Description] nvarchar NOT NULL
Which gives me the following error when I run it in Management Studio
Msg 5074, Level 16, State 1, Line 1 The index "IX_Description" depends on the Description column. Msg 4922, Level 16, State 9, Line 1 ALTER TABLE ALTER COLUMN The description failed because one or more objects access this column.
How can I get the jump code to remove the index and then change it and then rebuild the index?
I am using SQL Server 2008 R2
Is something like this possible?
DropIndex("dbo.Sites", "IX_Description"); AlterColumn("dbo.Sites", "Description", c => c.String(nullable: false, maxLength: 450)); CreateIndex("dbo.Sites", "Description", unique: true); I think you can also do SQL direct as shown below.
Sql("DROP INDEX [IX_Description] ON [dbo].[Sites] WITH ( ONLINE = OFF )"); Which may be useful if you want to add a check that the index exists or something else.