Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework 6.0 CreateDatabaseIfNotExists Code first to create database

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.

like image 344
Sanj Avatar asked Oct 23 '13 15:10

Sanj


People also ask

Which is best code first or database first?

This is a big one. Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.

Is Entity Framework code First?

For those developers, Entity Framework has a modeling workflow referred to as Code First. Code First modeling workflow targets a database that doesn't exist and Code First will create it. It can also be used if you have an empty database and then Code First will add new tables to it.

What is a code first database?

Code-First is mainly useful in Domain Driven Design. In the Code-First approach, you focus on the domain of your application and start creating classes for your domain entity rather than design your database first and then create the classes which match your database design.


1 Answers

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>());
like image 95
Sanj Avatar answered Sep 21 '22 18:09

Sanj