The Wild

Apply EF Core Migrations from Code: Step-by-Step

· 4 min read · Mammals

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Applying EF Core migrations from code means running database schema updates programmatically at application startup, rather than using the dotnet CLI or Package Manager Console. This is useful for self-hosted apps, test environments, or when you want the database to be automatically up to date on first run. You'll need an existing EF Core DbContext and at least one migration already created.

What You'll Need

  • An ASP.NET Core or .NET console application with EF Core installed.
  • A DbContext class (e.g., AppDbContext) configured with a database provider (SQL Server, SQLite, etc.).
  • At least one migration already generated via dotnet ef migrations add or Add-Migration.
  • Access to the target database connection string.

Step-by-Step

  1. Add the EF Core namespace. In the file where you'll run migrations (typically Program.cs or your startup class), add using Microsoft.EntityFrameworkCore;.
  2. Create a method to apply migrations. Write a helper method that takes a DbContext and calls Database.Migrate(). For example:
    public static void ApplyMigrations(AppDbContext db)
    {
        db.Database.Migrate();
    }
  3. Instantiate your DbContext. In your application entry point, create an instance of your DbContext using the options builder. For example:
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseSqlServer(connectionString)
        .Options;
    using var db = new AppDbContext(options);
  4. Call the migration method. Invoke your helper method before you start using the database. In a console app, place it right after the DbContext is created. In ASP.NET Core, do it in Program.cs after building the host but before app.Run().
  5. Handle the database creation (optional). If the database doesn't exist, Migrate() will create it automatically (provided the provider supports it, like SQL Server or SQLite). No extra step needed.
  6. Run your application. Start the app. The migration will run synchronously, applying any pending migrations. If there are none, it does nothing.
  7. Verify the schema. Check your database to confirm tables and columns are created or updated as expected.

Common Mistakes

  • Forgetting to call Migrate() – The method does nothing unless explicitly called.
  • Calling Migrate() on every request – It should be called once at startup, not in a request pipeline.
  • Using EnsureCreated() instead of Migrate() – EnsureCreated() creates the database if it doesn't exist but does not apply migrations. Use Migrate() for migrations.
  • Not disposing the DbContext – Always use using or dispose to avoid connection leaks.
  • Ignoring migration errors – If a migration fails, the database may be left in an inconsistent state. Handle exceptions.

Tips

  • Wrap in a try-catch to log any migration errors and fail gracefully.
  • Consider using a separate service for database initialization, especially in larger apps.
  • Use MigrateAsync() for async startup if your app supports async.
  • For production, consider running migrations as part of a deployment script instead of at startup to avoid downtime.
  • Test with a local database before deploying to ensure migrations are idempotent.

Troubleshooting

  • “No database provider has been configured” – Make sure you set up the DbContext options correctly (e.g., UseSqlServer).
  • “Migrations are pending” but nothing happens – Check that your DbContext is pointing to the correct database and that migrations are in the same assembly. If not, specify the assembly in the options.
  • “The model backing the context has changed” – This means your code model differs from the last migration. Create a new migration with dotnet ef migrations add and then apply it.
  • Database connection timeout – Ensure the connection string is correct and the database server is reachable.
  • Migration fails with a SQL error – Check the inner exception for details. Common issues: table already exists, missing permissions, or invalid column types.
  • Multiple DbContexts – If you have more than one, you need to call Migrate() on each one separately.

Frequently Asked Questions

Can I apply migrations without stopping the application?

Yes, Migrate() is designed to be safe to run while the app is running, but it may lock tables temporarily. For zero-downtime, use a separate deployment step.

What if I have multiple databases?

You need to create a DbContext for each database and call Migrate() on each. Alternatively, use a connection string per environment.

Does Migrate() create the database?

Yes, if the database doesn't exist, it will be created (for most providers). If you want to avoid that, check db.Database.Exists() first.

Can I roll back a migration applied from code?

Yes, you can use db.Database.Migrate(targetMigration) to roll back to a specific migration. But be careful with data loss.

Is it safe to run Migrate() in production?

It is common, but you should test thoroughly. For critical systems, consider running migrations as part of a controlled deployment process.

How do I apply migrations in a background service?

In a hosted service, you can inject your DbContext and call Migrate() in the StartAsync method.