EF 6 CodeFirst Migrations Not Working

c# ef-migrations entity-framework

Question

Ok, so I've read the other threads and I'm still not getting anywhere. I have my project set as Startup, I have a connection string in the App.config. I'm using LocalDb in VS2013.

If I delete my database, it creates it ok, BUT, if I try

 PM> Enable-Migrations 

it tells me that Migrations have already been enabled in project TestCodeFirst. If I then try

 PM> Update-Database 

it tells me No migrations configuration type was found in the assembly 'TestCodeFirst', and suggests that I try to Enable-Migrations. I have tried adding the -Force parameter. The Migrations folder has only Configuration.cs, and in that file, I've tried setting AutomaticMigrationsEnabled both true and false, with no difference. I'm not lost, cause I can always delete my DB and rerun, but I don't see any way to make the migrations feature work as advertised. Confession: At one point, I took PM's suggestion and tried deleting the Migrations folder. That may have been a mistake.

I have this code snippet in my Program.cs file (I'm just testing this in a console app):

class Program
{
    static void Main(string[] args)
    {
        using (TestContext db = new TestContext())
        {
            ...
            Db.ThisOrThat.Add(stuff);
            Db.SaveChanges();
            ...
        }
    }
}
1
3
4/8/2014 3:07:38 AM

Accepted Answer

The Entity Framework Code First approach creates your database automatically, a table will be automatically added to the database by the Code First that is helpful to record the schema of database synchronization with the related model class. Entity Framework throws an error, the database is not synchronized with the class.

To perform the Code First Migration in the database:

  • Delete the MDF file of the database

  • Open Package Manager Console and write the following command

    Enable-Migrations -ContextTypeName ConsoleApp.Models.TestContext

  • It creates the Configurations.csclass, then you can edit your code

  • After Building the application enter the following command in the Package Manager Console:

    add-migration Initial

    update-database

Note: If you receive an error then you need to ensure that the mdf file is deleted permanently from the App_Data folder. Otherwise you can go to the SQL Server Object Explorer, expand the localDb server and in the Database option ensure that the mdf file is deleted.

  • Debug the appliction
4
4/8/2014 4:48:12 AM

Popular Answer

You'll need to run the "Add-Migration" command that will actually add the migration that the 'Update-Database' command will run:

Code First Migrations

"Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created"



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