Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9214009
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T01:52:49+00:00 2026-06-18T01:52:49+00:00

We are running Entity Framework 5 with Code First and Migrations Enabled . Running

  • 0

We are running Entity Framework 5 with Code First and Migrations Enabled. Running with the database initializer: MigrateToLatestVersion

We have several customers live that run on the latest stable branch. While we develop new code in our trunk/master, we sometimes have the need to connect to the customers database running on branched code, fx. to debug some sort of data bug.

This can be “dangerous” if someone forgot to switch to the branch the customer is running, because migrations will then upgrade the customers database to fit whatever code that person is running.

One solution would be to run another initializer that doesnt migrate to the latest version. But that would mean a lot more work when we deploy new systems to new customers or someone new joins the team and needs go get up and running.

We were thinking of solving this problem by having a bool in the app.config to set if the code should “Migrate To Latest Version” and then always have that to false for development, and then transforming it when deploying to customers.

That way we get the benefit of still having the database updating to the newest version automaticly, but not the danger of a developer accidentally connecting to a system of an older version of the code, and migrations destroying that database.

So now that we have that, we basicly need to check this:

(simplified code)

if(Config.MigrateToLatestVersion || !databaseExists) 
{
  var initializer = new MigrateToLatestVersion<MyContext,MigrationConfiguration>();
  Database.SetInitializer(initializer);
  using(var context = new MyContext())
  {
    context.Database.Initialize(true)
  }
}

My question was going to be about how to check if the database exists without running migrations, but i found out you can do this:

Database.SetInitializer<MyContext>(null);
var context = new MyContext();
var databaseExists = context.Database.Exists();

But if i only run the MigrateToLatestVersion initializer when the database doesnt exist or when i manually run Update-Database from the package-manager console.

I have 2 problems, first: I no longer get an exception saying if my model is different from the database, which i would still like.
second: it doesnt run the seed method located in my MigrationConfiguration, which i might still want to run.

Any suggestions on how i can still run the Migrations Initializer to get all the benefits, but still have something that prevents someone from potentially breaking our production environments by accident?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T01:52:50+00:00Added an answer on June 18, 2026 at 1:52 am

    So the solution i went with was to make a new DatabaseInitializer called MigrateDatabaseToLatestIfLocal

    Looking how the MigrateDatabaseToLatestVersion initializer worked, i did something very similar, with the difference of checking if the database exists and if we were running locally or remote (With the help of config transformations to determine this. The remote system has it’s datasource transformed in the config file.)

    public class MigrateDatabaseToLatestIfLocal<TContext, TMigrationsConfiguration> : IDatabaseInitializer<TContext>
            where TContext : DbContext
            where TMigrationsConfiguration : DbMigrationsConfiguration<TContext>, new()
        {
            private DbMigrationsConfiguration _config;
    
            public MigrateDatabaseToLatestIfLocal()
            {
                this._config = (DbMigrationsConfiguration)Activator.CreateInstance<TMigrationsConfiguration>();
            }
    
            public MigrateDatabaseToLatestIfLocal(string connectionStringName)
            {
              MigrateDatabaseToLatestIfLocal<TContext, TMigrationsConfiguration> databaseToLatestVersion = this;
              var instance = Activator.CreateInstance<TMigrationsConfiguration>();
              instance.TargetDatabase = new DbConnectionInfo(connectionStringName);
                databaseToLatestVersion._config = instance;
            }
    
            public void InitializeDatabase(TContext context)
            {
                var databaseExists = context.Database.Exists();
    
                var migrator = new DbMigrator(this._config);
                var pendingMigrations = migrator.GetPendingMigrations().OrderByDescending(s => s);
                var localMigrations = migrator.GetLocalMigrations().OrderByDescending(s => s);
                var dbMigrations = migrator.GetDatabaseMigrations().OrderByDescending(s => s);
    
    
                var isRemoteConnection = FunctionToFindOutIfWeAreRemote(); //here we check the config file to see if the datasource is a certain IP, this differentiates locally and remotely because of config tranformation.
    
                if (isRemoteConnection && databaseExists)
                {
                    if (pendingMigrations.Any())
                    {
                        throw new MigrationsException("You are not allowed to automatically update the database remotely.")
                    }
                    if (localMigrations.First() != dbMigrations.First())
                    {
                        throw new MigrationsException("Migrations in code and database dont match, please make sure you are running the code supported by the remote system. ");
                    }
                }
                else
                {
                    //we are local, fine update the db and run seeding.
                    //we are remote and the db does not exist, fine update and run seed.
                    migrator.Update();
                }
            }
        }
    

    This might be a very special case, but to me it provides some safety when running code first migrations, that make sure you dont just randomly migrate a live environment accidently

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've enabled code-first migrations on my entity framework project, and have added several migrations
I am doing entity framework (v 5) code first migrations, on an MVC 4
I am using SQL Azure as database with code first technique of Entity framework
I'm running Entity Freamework Code First Migrations. When trying to run the application I
I'm running into an issue with Entity Framework code-first in MVC3. I'm hitting this
I'm trying to get Entity Framework Code First to create a database for me
We are using Entity Framework Code First, and I am running into issues trying
I have built up a code-first model using Entity Framework 5. The classes have
I'm using the latest and greatest Entity Framework Code First and I'm running into
I'm using Entity Framework 4.1 Code First. In my entity, I have three date/time

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.