Frank Modica
Frank Modica

Reputation: 10516

Can "Script-Migration" create the database in .NET Entity Framework Core?

I am creating my database relationships using the code-first approach in .NET Entity Framework Core. Locally, if I run Add-Migration with Update-Database, the database is created with all of the correct tables.

For deployments, instead of running Update-Database, I'd like to use Script-Migration to generate SQL scripts. But the generated scripts assume a database already exists.

Here's what I've tried:

Add-Migration InitialMigration -Context MyContext

Script-Migration 0 InitialMigration -Context MyContext

But the generated scripts begin with table creation:

IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL
BEGIN
    CREATE TABLE [__EFMigrationsHistory] (
...

I read that I shouldn't combine Database.EnsureCreated() with migrations, so what is the best practice? Should I write the database creation portion myself?

Upvotes: 3

Views: 2756

Answers (1)

bricelam
bricelam

Reputation: 30375

Yes, write it yourself. Creating databases is very inconsistent between providers and can't always be done using SQL. Hence, EF Core leaves it up to the user when creating the Migrations script.

Upvotes: 4

Related Questions