Development and production databases

Me and my team are currently on a project where we are using Entity Framework 4.1 (Code First). We want to write some tests, but we don't want them to run on our primary database as we have a team in Singapore writing a client for what we do and they keep hitting that database all the time.

So, to avoid interfering with our tests, we would like to have a different database to test. How do we handle the second database when using Entity Framework? We want the solution to be semi-automatic (at least), so we don't have to mess with the Web.config every time we need to run tests.


source to share

2 answers

With web.config it is possible to start an error prone process ... unless you are using the web.config Transformations that is.

I would create a new "Test" configuration for your project in Visual Studio ... it could be a copy of your existing development configuration (or Debug / Release, whatever). Then right-click the Web.config file in Solution Explorer and click Add Config Transforms . Follow the instructions here on how to write a transform file. If you only need to change the EF connection string for your test environment, it will look something like this in web.Test.config:

<?xml version="1.0"?>
<configuration xmlns:xdt="">
    <add name="AdventureWorksEntities" 
     provider=System.Data.SqlClient;provider connection string='Data Source=TestDB;
     Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
     multipleactiveresultsets=true'" providerName="System.Data.EntityClient" 
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>


Just make sure you build the correct configuration when you want to run your tests.

Configuration Manager

There is also a Visual Studio add-in SlowCheetah This makes this whole process very seamless in the IDE.



The solution was taken from this post:

//Get the connection string from app.config and assign it to sqlconnection string builder
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(((EntityConnection)context.Connection).StoreConnection.ConnectionString);
sb.IntegratedSecurity = false;
sb.UserID ="User1";
sb.Password = "Password1";

//set the object context connection string back from string builder. This will assign modified connection string.
((EntityConnection)context.Connection).StoreConnection.ConnectionString = sb.ConnectionString;


This allows you to change the connection string at runtime. There are several other possible solutions:

  • Create a wrapper property around the connection string. From tests, set it to a different value.
  • Use #IF TEST primes to specify the correct connection string at compile time


All Articles