我将如何更改我的代码优先 ASP.NET MVC 应用程序以使我的数据库位置相对于我的应用程序主目录?

How would I alter my code-first ASP.NET MVC app to make my database location relative to my app home directory?

这是我问的另一个问题的一个分支,有人建议,当我向他发送我的代码优先应用程序时,为了让 SQL 服务器数据库可供我的讲师访问,我应该 "have a database location which is relative to [my] application home directory."

所以我用谷歌搜索了那个确切的短语,但没有找到与我的情况相关的步骤。这可能比我做的要简单,但是我到底需要调整什么才能使数据库位置相对?这与 web.config 中的连接字符串有关吗?

我的连接字符串如下,StudentContextDB 是 运行 应用程序自动生成的数据库:

<connectionStrings>
    <add name="StudentContext"
         providerName="System.Data.SqlClient"
         connectionString="Data Source=DESKTOP-P3ECVON\SQLEXPRESS;Initial Catalog=StudentContextDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\StudentContextDB.mdf" />
</connectionStrings>

DESKTOP-P3ECVON 是我的服务器名称。我怎样才能使数据库位置相对,或者以其他方式使下载此应用程序的任何人都可以 运行 它正确并在他们自己的计算机上生成数据库?

再次,如果这非常明显而我错过了,我深表歉意。在此先感谢您的任何建议或指导!

您可以按如下方式编写您的连接字符串:

<add name="ConnectionStringName"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=(LocalDB)\mssqlLocalDb;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;InitialCatalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True" />

根据您的以下问题,

DESKTOP-P3ECVON is my server name. How can I make the DB location relative, or otherwise make it so anyone who downloads this app can run it properly and have the database be generated on their own computer?

如果你想使用 SQL Server Express Database 然后使用 dot(.) 而不是硬输入服务器名称如下:

<add name="ConnectionStringName"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />

这会将 DatabaseFileName.mdf 文件添加到项目的 App_Data 文件夹中。

更多详情:SQL Server Connection Strings for ASP.NET Web Applications