HomeAmir Hossein Shekari (Vanenshi)

Protect Production Database from Wrong Migrations

  • #dotnet
  • #database
Amir Hossein Shekari (Vanenshi)

Amir Hossein Shekari

1 min read
Protect Production Database from Wrong Migrations

As a .NET developer, I had a close call when I applied a migration to my production database without changing the database connection string. I was mortified when I realized my mistake, but I quickly got to work finding a solution to prevent it from happening again.

That's when I came up with the idea to add a console message that displays the migration details before applying it. This simple addition gives me the chance to review the migration details and ensure that I am working with the correct database before making any changes.

With this new safeguard in place, I can breathe easy knowing that my production database is safe from accidental alterations. It just goes to show that sometimes the simplest solutions can be the most effective.

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    public ApplicationDbContext CreateDbContext(string[] args)
        // ... Some code to generate dbContextBuilder
        var context = new ApplicationDbContext(dbContextBuilder.Options);

        // This is where magic happens
        var pendingMigrations = context.Database.GetPendingMigrations();

        Console.WriteLine("This command is going to apply migrations with following details");

        Console.Write("ConnectionString: ");
        Console.ForegroundColor = ConsoleColor.Yellow;

        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine(string.Join("\n\t", value: pendingMigrations.ToArray()));

        Console.WriteLine("Do You confirm? (Y/N)");
        var userInput = (Console.ReadLine());

        if (userInput is "Y" or "y")
            return context;

        Console.ForegroundColor = ConsoleColor.Red;
        return null;
  • More info about the `ApplicationDbContextFactory`

Amir Hossein Shekari

Written by Amir Hossein Shekari (Vanenshi)

Vanenshi is a Github Star 🌟 and Design Engineer 👨🏽‍💻. He is passionate about helping people build an accessible web faster. Sage is the author of Chakra UI, a React UI library for building accessible experiences.

Amir Hossein Shekari

Tech-savvy Software Engineer driven by a love for problem-solving and innovation.

All rights reserved © Amir Hossein Shekari 2024