Click here to Skip to main content
13,351,896 members (88,313 online)
Click here to Skip to main content
Add your own
alternative version


4 bookmarked
Posted 4 Feb 2013

IDbContextFactory which gets Connection String at runtime and triggers Automatic Migrations

, 4 Feb 2013
Rate this:
Please Sign up or sign in to vote.
Sample code showing how to implement IDbContextFactory for retrieving ConnectionString at runtime and trigger automatic migrations. For use with DI and IoC or if you have different databases with the same model.


This sample code is for using Entity Framework 5 when you want to specify the Context you use (Connection, Initializer, and Configuration) at Runtime.


It took me two weeks of gathering Information how to run Automatic Migration from code without Package Manager Console and how to do this when I want to specify the Connection String at runtime. Further I don't want to use any .config files or others static configurations.

Using the code

I use different ContextFactories for testing, development and production. In combination with Ninject an UnitOfWork pattern I'm able use the right context for the right purpose. Here a sample code of my Factory for Unit Testing. 

The DbContext (WPH_BusinessContext in this case) itself just contains the DbSets and the OnModelCreating handler to specify the mappings done in the FluentAPI. 

Note: the Migration will throw a Exception if there is data loss. There is also a sample how to set DbInitializers, but it's commented out.  

public class TestDBContextFactory : IDbContextFactory<WPH_BusinessContext>
  public WPH_BusinessContext Create()
     //set connection string at runtime here
     string connectionString = Properties.Settings.Default.TestDB;
     var connectionInfo = new DbConnectionInfo(connectionString, "System.Data.SqlClient");

     bool doInitialize = false;
     //Set initializer here
     //Database.SetInitializer<WPH_BusinessContext>(new DropCreateDatabaseAlways<WPH_BusinessContext>());
     //doInitialize = true;       

     var contextInfo = new DbContextInfo(typeof(WPH_BusinessContext), connectionInfo);
     var context = contextInfo.CreateInstance();
     context.Configuration.LazyLoadingEnabled = true;
     context.Configuration.ProxyCreationEnabled = true;

     if (doInitialize)

     bool doMigration = false;
        doMigration = !context.Database.CompatibleWithModel(true);
     catch (NotSupportedException)
        //if there are no metadata for migration
        doMigration = true;

     if (doMigration)
        var migrationConfig = new DbMigrationsConfiguration<WPH_BusinessContext>();
        migrationConfig.AutomaticMigrationDataLossAllowed = false;
        migrationConfig.AutomaticMigrationsEnabled = true;
        migrationConfig.TargetDatabase = connectionInfo;
        var migrator = new DbMigrator(migrationConfig);

     return context as WPH_BusinessContext;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer Omicron electronics
Austria Austria
2006-2011 HTL Dornbirn - Betriebsinformatik
2011 Cisco CCNA
2011/12 TU Wien - Software Engineering (1 Semester)

Software Engineer at suite (
ASP.NET, Windows Azure, MS SQL Server

since 2013
Software Engineer at Omicron electronics (

You may also be interested in...


Comments and Discussions

QuestionCan you share details on how you use it with Ninject? Pin
dudey_vish27-Sep-17 20:03
memberdudey_vish27-Sep-17 20:03 
QuestionInstantiating the DbContext with a Connection String Pin
garyhalb18-Mar-13 4:56
membergaryhalb18-Mar-13 4:56 
AnswerRe: Instantiating the DbContext with a Connection String Pin
retsnoM18-Mar-13 6:21
memberretsnoM18-Mar-13 6:21 
QuestionThank You so much Pin
JUlfeng15-Mar-13 17:29
memberJUlfeng15-Mar-13 17:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 4 Feb 2013
Article Copyright 2013 by retsnoM
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid