How to set the connection string to the local database so that each time you manually change the path?

There is such a connection string:

<connectionStrings> <add name="LibraryModelContainer" connectionString="metadata=res://*/LibraryModel.csdl|res://*/LibraryModel.ssdl|res://*/LibraryModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\LibrarySystem.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> 

Connection string was created automatically. If you run my project with this connection string, an exception occurs in the program:

Internal exception 1: SqlException: Answered: C: \ Users \ Cuurjol \ Desktop \ 123 \ BACKUP LIBRARY \ Library \ Library \ bin \ Debug \ LibrarySystem.mdf failed. It cannot be opened, or it is located on UNC share.

I have been looking for a solution to this problem on the Internet for a long time, I found that instead of attaching attachdbfilename = | DataDirectory | \ LibrarySystem.mdf I should write the whole path to the file, for example:

 attachdbfilename=C:\Users\Cuurjol\Desktop\123\BACKUP LIBRARY\Library\Library\LibrarySystem.mdf 

But I don’t want to write the path because the folder with the project can be located anywhere, but I need to somehow write in App.config so that there is always a connection to the database, regardless of the location of the project itself on the hard disk.

How can I do that? And why does the generated database connection string not work when the project starts?

    1 answer 1

    You can set the relative path to the database using the substitution variable | DataDirectory |. Its value depends on the type of project:

    • For a regular desktop application, the path to the folder with the .exe file
    • For a ClickOnce application, the path to the special data folder
    • For ASP.NET applications - the path to the folder App_Data

    You can override the value in the code:

     AppDomain.CurrentDomain.SetData("DataDirectory", newpath) 

    See this article , documentation .

    Regarding the error of an attempt to attach an auto-named database for file ... failed. She may have many reasons. The file does not exist, the SQL service account does not have enough rights to open it, a database with the same name already exists, etc. Usually using the AttachDbFileName property, especially with an autogenerated database name, is not a good practice. It is better to create a deployment program or script that will attach the database once with an explicitly specified name, and set the Initial Catalog property in the program. So it will be much easier to maintain the program.