faujong
faujong

Reputation: 1127

Remove index thru EntityFramework CodeFirst Migration

We now use EntityFramework CodeFirst Migration. Our database table and index was created long time ago, before we use EntityFramework CodeFirst Migration. Our table is myTable, with a column vchMyColumnA and index ColumnA. Since we used EntityFramework CodeFirst Migration, we have used EntityFramework CodeFirst Migration to add new columns to myTable.

We need to drop Index ColumnA.

  1. Do we need to do it thru EntityFramework CodeFirst Migration, or can we just run a script to drop the index ?

  2. If we need to drop the index thru EntityFramework CodeFirst Migration, how can I do it ? In Package Manager Console, I typed add-migration DropColumnAIndex, and open the migration code DropColumnAIndex, and added this code:

    public partial class DropColumnAIndex : DbMigration
    {
    
        public override void Up()
        {
            DropIndex("dbo.myTable", new[] { "ColumnA" });
        }
    
        public override void Down()
        {
            CreateIndex("dbo.myTable", "vchMyColumnA");
        }
    }
    

Then I typed update-database. There is no error, and I can see the migration in the database (select * from __MigrationHistor), but index ColumnA is still there.

Thank you.

Upvotes: 1

Views: 4275

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

Sorry, hard to write this in a comment. You can inject the equivalent SQL into your migration:

public override void Up()
{
    Sql("DROP INDEX ColumnA ON [dbo].[myTable];"); 
}

Upvotes: 2

Related Questions