An object-oriented programming language developed by Microsoft that can be used in .NET.
Thanks for detailed explanation-this is a common limitation when using DataDirectory since it supports only a single substitution value per AppDomain
Root Cause
|Data Directory| is a global setting. Once you set it (via AppDomain.CurrentDomain.SetData("DataDirectory", path), it applies to all connection string using that placeholder. That's why both .mdf files are being resolved to the same directory.
Recommended Approach
You should avoid relying on | DataDirectory| for scenarios where multiple database files reside in different locations. Instead, dynamically build your connection strings at runtime with explicit paths.
Solution 1: Build connection Strings Dynamically
At application startup:
Dim commonDbPath As String = System.IO.Path.Combine(Application.StartupPath, "common.mdf")
Dim variablePath As String = userSelectedPath 'e.g. from the folder picker
Dim commonCpnnStr As String = $"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={commonDbPath};Integrated Security=True;Connect Tomeout=30"
Dim variableConnStr As String = $"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={variableDbPath};Integrated Security=True;Connect Tomeout=30"
This ensures each database points to its correct directory independently.
Solution 2: Store Base Paths in Config (Optional)
In App.config, store partial strings:
<appSettings>
<add key="CommonDbPath" value="common.mdf"/>
</appSettings>
Then resolve full paths in code:
Dim basePath = Application.StartupPath
Dim commonDb = Path.Combine(basePath, ConfigurationManager.AppSettings("CommonDbPath"))
What not to do:
- Avoid trying to use multiple DataDirectory values (e.g., DataDirectory1, DataDirectory2)- this is not supported
- Avoid switching DataDirectory at runtime before each connection - this is unsafe and can lead to unpredictable behavior.
if the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".