Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 276
Anuj sharma Avatar asked Jan 25 '16 05:01

Anuj sharma


2 Answers

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

like image 69
Neeraj Sharma Avatar answered Sep 22 '22 05:09

Neeraj Sharma


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()
    {
    }
  }
}
like image 41
megamaiku Avatar answered Sep 19 '22 05:09

megamaiku