How to specify a connection string for a DatabaseInitializer


  • In the code below I pass a valid connection string name in the class constructor. However when InitializeDatabase is called the passed context has a connection string pointing to localdb (i.e. not the connection string who's name I passed in). How do I get context to have the right connection string?

    internal class VerifyDatabaseInitializer<TContext, TConfiguration> : IDatabaseInitializer<TContext>
            where TContext : DbContext
            where TConfiguration : DbMigrationsConfiguration<TContext>, new()
            private readonly DbMigrationsConfiguration _configuration;
            public DatabaseStatus DBStatus { get; private set;}
            public VerifyDatabaseInitializer(string connectionStringName) 
                _configuration = new TConfiguration { TargetDatabase = new DbConnectionInfo(connectionStringName) };
                DBStatus = DatabaseStatus.Unknown;
            void IDatabaseInitializer<TContext>.InitializeDatabase(TContext context)
                string errorMsg = String.Empty;
                if (context.Database.Exists())
                    if (context.Database.CompatibleWithModel(false))
                        DBStatus = DatabaseStatus.ConsistentWithModel;
                        DBStatus = DatabaseStatus.NotConsistentWithModel;
                    DBStatus = DatabaseStatus.DoesNotExist;

    Here is the code that calls the above:

    var initializer = new VerifyDatabaseInitializer<FFFContext, FFFConfiguration>(StateManager.ConnectionStringName); // correct connection string name here
    FFFContext context = new FFFContext(StateManager.ConnectionString); // correct connection string or connection string name here
    context.Database.Initialize(true); // wrong connection string in the initializer

    • Edited by SWheaties Sunday, January 26, 2014 4:07 PM
    Sunday, January 26, 2014 5:49 AM


  • My bad, I was not passing the connection string to dbcontext in the constructor of my context.

    • Marked as answer by SWheaties Sunday, January 26, 2014 5:16 PM
    Sunday, January 26, 2014 5:16 PM