I'm trying to use EF code first migrations to build a database if it doesn't exist. So far, I've Enabled-Migrations
successfully. I've also used Add-Migrations
to make an initial migration that builds the database. The script is in the Migrations direction and looks correct.
This is the body of my Main method
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>());
var directConfigContext = new MyDbContext();
Everything I've read that says this is all I need. MyDbContext
is in app.config
and looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="MyDbContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=DbConfig;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Additionally, if I use the DbMigrator class provided by EF, the database is built correctly (presumably using the initial database migration script).
// This is how it actually works including creating the database if it doesn't exist.
var dbMigrator = new DbMigrator(new Configuration());
dbMigrator.Update();
From what I understand, setting the initializer on MyDbContext
and afterward instantiating that DbContext
should create the database to the latest migration... what am I missing?
Instantiating a DbContext does not execute the initializer bound to it. Instead, you need to either update the database or call the initializer on the underlying database directly.
MyDbContext.MyEntity.Add(new MyEntity { Name = "Nelson" });
// Or
MyDb.Context.Database.Initialize(true); // force the initialization
The accepted answer will solve the problem for other people, but I was having this same problem with a different reason: I deleted my database and modified the model by changing some classes in my DbContext
.
When I ran my application, and it instanced and tried to use the DbContext
for the first time, the database was not created because the last migration didn't reflect the last changes I'd made in the DbContext
. To solve the problem I simply added a new migration by running the Add-Migration
command on the Package manager console, and the next time the application started the database was correctly created and sed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With