EntityFramework 6.0 CreateDatabaseIfNotExists Code first to create database

c# entity-framework powershell


What am I doing wrong. I have got a user DbContext setup and working when I originally created the Code-First with powershell it all worked fine.

I implemented Database Initializer as expected on application start.

Database.SetInitializer<UserDbContext>(new CreateDatabaseIfNotExists<UserDbContext>());

Just to test out if it really creates the database I actually dropped the database and now I am stuck the database will not be created. I am using SQL Server 2012, any idea what could be wrong.

The error message I am getting is

System.InvalidOperationException: Migrations is enabled for context 'UserDbContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.

I have tried the same from Package Manager console and it is still give me the same message.

10/23/2013 3:46:47 PM

Accepted Answer

Finally figured the solutions, not sure why or what. Changed my Database initializer to MigrateDatabaseToLatestVersion instead of CreateDatabaseIfNotExists worked.

Database.SetInitializer<UserDbContext>(new MigrateDatabaseToLatestVersion<UserDbContext, Configuration>());
10/23/2013 5:07:52 PM

Popular Answer

Edit: With your new error message the problem comes from you having migrations enabled and already ran a migration (probably the first creation of the database) and since you dropped the DB the migration history has been lost. If your not using Automatic migrations you can not go in and make changes to the database your self and expect code-first to know about it. Try disabling migrations and re-enabling them to see if that clears out the migration history.

You will need to make a call into the DB either as a read or insert of data for the DB to initially be created. The code you use only tells EF how to deal with a database if one does not exist when it tries to find it. For me I use the method outlined at http://www.codeproject.com/Tips/411288/Ensure-Your-Code-First-DB-is-Always-Initialized

Related Questions


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