在实体框架中运行时更改连接字符串中的数据库名称
在我的项目中,我想在使用 EntityFramework 的 DAL 层上运行一些单元测试。我在每次运行测试之前从脚本创建一个新数据库(以便在进行测试时始终拥有相同的初始数据)。在测试结束时,该数据库将被删除,(所有这些都是在 [ClassInitialize()] 和 [ClassCleanup()] 属性的帮助下自动生成的。
生成的数据库始终具有不同的名称,例如 TestDB-2009-01 -31--12-00-00,为了不与我同事的测试数据库冲突,
我遇到的实际问题是我还没有找到一种方法来告诉EntityFramework连接到生成的数据库(名称)现在它连接到 app.config 文件中指定的连接字符串,这当然是正常的,因为我正在做这些测试,所以我正在寻找可以从外部完成的东西。 DAL dll(无需直接在 EF 上下文上设置任何内容),
非常感谢
。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建 ObjectContext 时,需要使用以 ConnectionString 作为参数的构造函数重载。
您可以使用 EntityConnectionStringBuilder 构建此 ConnectionString。更具体地说,假设您的基础数据库是 SQL Server,您可以使用 SqlConnectionStringBuilder 构建 EntityConnectionStringBuilder.ProviderConnectionString 的值。
下面是一些构建 SQL Server 连接字符串的代码
下面是一些构建 Entity ConnectionString 的代码:
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
And here's some code that builds the Entity ConnectionString: