How and where to call Database.EnsureCreated and Database.Migrate? How and where to call Database.EnsureCreated and Database.Migrate? asp.net asp.net

How and where to call Database.EnsureCreated and Database.Migrate?


I think this is an important question and should be well answered!

What is Database.EnsureCreated?

context.Database.EnsureCreated() is new EF core method which ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created and also it ensures it is compatible with the model for this context.

Note:This method does not use migrations to create the database. In addition, the database that is created cannot later be updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.

How did we do that with EF 6?

context.Database.EnsureCreated() is equivalent to the below listed approaches of EF 6:

  1. Package Manager Console:

    Enable-Migrations -EnableAutomaticMigrations. Add-Migration/Update-Database.

  2. From code:

    Database.SetInitializer CreateDatabaseIfNotExists

or

With DbMigrationsConfiguration and set AutomaticMigrationsEnabled = true;

What is Database.Migrate?

Applies any pending migrations for the context to the database. Will create the database if it does not already exist.

How did we do that with EF 6?

context.Database.Migrate() is equivalent to the below listed approaches of EF 6:

  1. Package Manager Console:

    Update-Database -TargetMigration

  2. With a custom DbMigrationsConfiguration:

    AutomaticMigrationsEnabled = false; or with DbMigrator.

Conclusion:

If you are using migrations there is context.Database.Migrate(). If you don't want migrations and just want a quick database (usually for testing) then use context.Database.EnsureCreated()/EnsureDeleted().


With the information that James P and Bassam Alugili provided, what I ended up doing was to add these lines of code to the Configure method in the Startup class (Startup.cs):

using (var scope =   app.ApplicationServices.CreateScope())using (var context = scope.ServiceProvider.GetService<MyDbContext>())    context.Database.Migrate();


Just as a foreward you should read this from Rowan Miller:

... EnsureCreated totally bypasses migrations and just creates the schema for you, you can't mix this with migrations. EnsureCreated is designed for testing or rapid prototyping where you are ok with dropping and re-creating the database each time. If you are using migrations and want to have them automatically applied on app start, then you can use context.Database.Migrate() instead.

According to answer here you need to add Globals.EnsureDatabaseCreated(); it to Startup.cs:

Startup function in Startup.cs:

public Startup(IHostingEnvironment env){    // Set up configuration sources.    var builder = new ConfigurationBuilder()            .AddJsonFile("appsettings.json")            .AddEnvironmentVariables();    if (env.IsDevelopment())    {        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.            builder.AddApplicationInsightsSettings(developerMode: true);    }    Configuration = builder.Build();    Globals.Configuration = Configuration;    Globals.HostingEnvironment = env;    Globals.EnsureDatabaseCreated();}

And define Globals.EnsureDatabaseCreated() as follows:

public static void EnsureDatabaseCreated()    {        var optionsBuilder = new DbContextOptionsBuilder();        if (HostingEnvironment.IsDevelopment()) optionsBuilder.UseSqlServer(Configuration["Data:dev:DataContext"]);        else if (HostingEnvironment.IsStaging()) optionsBuilder.UseSqlServer(Configuration["Data:staging:DataContext"]);        else if (HostingEnvironment.IsProduction()) optionsBuilder.UseSqlServer(Configuration["Data:live:DataContext"]);        var context = new ApplicationContext(optionsBuilder.Options);        context.Database.EnsureCreated();        optionsBuilder = new DbContextOptionsBuilder();        if (HostingEnvironment.IsDevelopment()) optionsBuilder.UseSqlServer(Configuration["Data:dev:TransientContext"]);        else if (HostingEnvironment.IsStaging()) optionsBuilder.UseSqlServer(Configuration["Data:staging:TransientContext"]);        else if (HostingEnvironment.IsProduction()) optionsBuilder.UseSqlServer(Configuration["Data:live:TransientContext"]);        new TransientContext(optionsBuilder.Options).Database.EnsureCreated();    }

To use context.Database.Migrate() see here or here.