FreddieMercury
FreddieMercury

Reputation: 191

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

This is an off-shoot of another question I asked, which one person suggested that in order for the SQL Server database to be accessible to my instructor when I send him my code-first app, I should "have a database location which is relative to [my] application home directory."

So I googled that exact phrase, and have not found steps on how to do that which seem relevant to my situation. This might be simpler than I'm making it, but what exactly do I have to adjust in order to make the database location relative? Does this have to do with the connection string in web.config?

My connection string is as follows, with StudentContextDB being the database that gets auto-generated by running the app:

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

Again, I apologize if this is exceedingly obvious and I'm missing it. Thanks in advance for any suggestions or guidance!

Upvotes: 0

Views: 37

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32139

You can write your connection string as follows:

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

According to your following question,

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?

if you want to use SQL Server Express Database then use dot(.) instead of hardly typed server name as follows:

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

This will add the DatabaseFileName.mdf file to the App_Data folder of the project.

For more details: SQL Server Connection Strings for ASP.NET Web Applications

Upvotes: 2

Related Questions