Change the database name in the connection string in Entity Framework during runtime.

.net entity-framework runtime

Question

I want to run some unit tests on the EntityFramework-using DAL layer in my project. Before each test run, I build a fresh database from scratch (in order to have always the same initial data when doing the tests). This database is deleted at the conclusion of the tests; this is done automatically with the aid of the [ClassInitialize()] and [ClassCleanup()] attributes.

In order to avoid confusion with the test databases of my colleagues, the produced database always has a unique name, such as TestDB-2009-01-31--12-00-00.

The real issue I'm having is that I haven't yet figured out how to instruct EntityFramework to establish a connection to the produced database (the name is generated at runtime). Currently, it establishes a connection to the connection string listed in the app.config file, which is obviously normal. In addition, I'm searching for anything that can be done from outside the DAL dll since I'm doing these tests (without setting anything on the EF context directly).

I really appreciate any assistance.

Thanks.

1
20
9/29/2009 4:12:42 PM

Accepted Answer

You must use the constructor overload that accepts a ConnectionString as an argument when creating the ObjectContext.

This ConnectionString may be created by using a EntityConnectionStringBuilder. More precisely, if the underlying database is SQL Server, you may construct the value for EntityConnectionStringBuilder using a SqlConnectionStringBuilder. ProviderConnectionString.

The code that creates the SQL Server connection string is provided here.

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

Additionally, the following code creates 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;
40
9/29/2009 5:10:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow