c# - 如何定义连接字符串以在当前文件夹中创建本地数据库?

标签 c# .net database-connection connection-string local-database

我当前的连接字符串是:

<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/

相关文章:

c# - 关键字 global::when adding reference

c# - 在后台线程上初始化单例的常见模式

python - 为多个数据库设置一个 MySQLdb 连接对象

c# - 托管 C++ 中奇怪的 GetLastError 返回

c# - 这是反序列化 Facebook JSON 字符串的好方法吗?

c# - 通过指定属性的唯一性从 List<> 获取对象

java - 没有找到合适的驱动程序调用 getConnection

asp.net - Microsoft Azure 中 ASP.NET Web App 的访问性能计数器

c# - 在 C# 中修改 .resx 文件

c# - UWP 等同于 uwp 中 FindAncestor 的函数