How can we delete a column from sql table by using code first approach in EF 6.0?

asp.net-mvc entity-framework sql

Question

By mistake I've added one column in my database Named as doj now if I want to drop that column from table using code first approach what should I do.

I've tried this things.

1- Removing the column definition from model.
2- Deleted Migration history.
3- Add-migration
4- Update database.

But still it is not reflecting in database? Where I made the mistake?

1
4
1/25/2016 5:45:23 AM

Accepted Answer

Don't need to delete migration history.

Just follow these steps

1: Remove properties from the model.
2: Run 'Enable-Migrations' in package manage console.
3: Next Run 'Add-Migration "MigrationsName"'. if any case it is showing 'The project  tesproject failed to build then build project again.
4: Now run 'Update-Database' 

It will surly effect on your code. Go with MSDN

8
1/25/2016 11:04:19 AM

Popular Answer

While Neeraj's answer is correct and in most cases works well, if that column has previous data in it, it will be removed from the index, but the data will still be there (and the column, for that matter).

To completely remove the column (and data in it), use the DropColumn() method. To accomplish this, create a new migration add-migration unwantedColumnCleanup and include the necessary code in the up() method, and then update-database.

namespace MyDB.Migrations
{
  using System;
  using System.Data.Entity.Migrations;

  public partial class unwantedColumnCleanup : DbMigration
  {
    public override void Up()
    {
        DropColumn("Table", "Column");
    }

    public override void Down()
    {
    }
  }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow