4

My current connection string is:

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

This works fine except the fact that the database is created in C:\Users\currentUser how do I change this so that it will be created in the same folder where the program runs or define a different location that I choose?

1 Answer 1

3

You are missing 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.

quote from 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.

try to change you connection string like something like this:

<add name="myConnectionString"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\CapacityDatabase.mdf;InitialCatalog=CapacityDatabase;Integrated Security=True;MultipleActiveResultSets=True" />

EDIT

|DataDirectory| is a placeholder, that in the case of the ASP.Net MVC template refers to the directory App_Data. This way it is possible to specify a relative path for your db file. You can define the value for |DataDictionary| like this:

AppDomain.CurrentDomain.SetData("DataDirectory", @"C:\XYZ\App_Data\"); 

but is not possible to use a relative path that point to a location higher in the directory structure.

Sign up to request clarification or add additional context in comments.

2 Comments

And how can I set DataDirectory to current folder?
Your DataDirectory will be appData in your solution, so the best choice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.