我正在使用 SQL Express 数据库作为 c# 单元测试项目的一部分。我的数据库位于此处:
./Databases/MyUnitTestDB.mdf
我想在 app.config
中使用相对路径或变量,而不是将连接字符串定义为:
AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf
我看到了 |DataDirectory|
的使用,但我认为这仅适用于 Web 应用程序是否正确?
我想在应用程序配置文件中控制它,因为在生产中应用程序使用托管的 sql 数据库。
最佳答案
谢谢大家,我结合了你们的回答。
在我的 app.config 文件中,我的连接字符串定义如下
<add name="MyConnectionString"
connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" />
在我的单元测试类中,我使用以下设置 DataDirectory 属性
[TestInitialize]
public void TestInitialize()
{
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));
// rest of initialize implementation ...
}
关于c# - SQL Express 连接字符串 : mdf file location relative to application location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3500829/