我当前的连接字符串是:
<connectionStrings>
<add name="myConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=CapacityDatabase.mdf;Integrated Security=True;Connect Timeout=10"
providerName="System.Data.SqlClient"/>
</connectionStrings>
这工作正常,除了数据库是在 C:\Users\currentUser
中创建的事实我如何更改它以便它将在程序运行的同一文件夹中创建或定义一个我选择的不同位置?
最佳答案
您缺少 AttachDBFilename=|DataDirectory|
DataDirectory| (enclosed in pipe symbols) is a substitution string that indicates the path to the database. It eliminates the need to hard-code the full path which leads to several problems as the full path to the database could be serialized in different places. DataDirectory also makes it easy to share a project and also to deploy an application.
引自 MSDN
Use the AttachDBFilename connection string keyword to add a database to your LocalDB instance. When using AttachDBFilename, if you do not specify the name of the database with the Database connection string keyword, the database will be removed from the LocalDB instance when the application closes.
尝试像这样改变你的连接字符串:
<add name="myConnectionString"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\CapacityDatabase.mdf;InitialCatalog=CapacityDatabase;Integrated Security=True;MultipleActiveResultSets=True" />
编辑
|数据目录|是一个占位符,在 ASP.Net MVC 模板的情况下,它指的是 App_Data 目录。这样就可以为您的 db 文件指定一个相对路径。 您可以定义 |DataDictionary| 的值像这样:
AppDomain.CurrentDomain.SetData("DataDirectory", @"C:\XYZ\App_Data\");
但不可能使用指向目录结构中较高位置的相对路径。
关于c# - 如何定义连接字符串以在当前文件夹中创建本地数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24406549/