views:

1300

answers:

1

Hello guys,

In my project I want to run some unit tests on the DAL layer that is using EntityFramework. I'm creating from scrips a new database before each run of the tests (in order to have always the same initial data when doing the tests). At the end of the tests, this database is dropped, (all is made automatically with the help of [ClassInitialize()] and [ClassCleanup()] attributes.

The generated database always has a different name, something like TestDB-2009-01-31--12-00-00, in order not to conflict with the test databases of my collegues.

The actual problem that I have is that I did not find yet a way to tell EntityFramework to connect to the generated database (the name is generated at runtime). Right now it connects to the connection string specified in the app.config file, which is normal, of course. And because I'm doing these tests, I'm looking for something that can be done from outside the DAL dll (without setting anything on the EF context directly).

Any help is greatly appreciated.

Thanks.

+6  A: 

When you create the ObjectContext, you will need to use the constructor overload that takes a ConnectionString as a parameter.

You can build this ConnectionString using an EntityConnectionStringBuilder. More specifically, assuming your underlying database is SQL Server, you can use a SqlConnectionStringBuilder to build up the value for EntityConnectionStringBuilder.ProviderConnectionString.

Here is some code that builds up the SQL Server connection string

var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "localhost";
scsb.InitialCatalog = "MyDB";
scsb.IntegratedSecurity = true;

And here's some code that builds the Entity ConnectionString:

var builder = new EntityConnectionStringBuilder();
builder.Metadata = "res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
Mark Seemann