Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

.net - change db name in connection string at runtime in Entity Framework

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...