基于服务的连接字符串在不同机器上发生变化

Service Based connection String that changes when on different machine

我有一个基于服务的数据库,默认连接字符串是

@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\James\OneDrive\Miller Veneers\Program\Current\HandHeld\SQLLibrary\MyDatabase.mdf;Integrated Security=True";

有效。我的问题是,当我将其更改为动态以便我可以在另一台计算机上使用它时,它停止工作。

我试过了

@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" +
                   (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) +
                    @"\MyDatabase.mdf;Integrated Security = True;");



@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=/MyDatabase.mdf;Integrated Security = True;


非常感谢!

我建议将其保存在配置文件中,然后在要更改数据库路径时从配置中更改用户名

你举的两个例子都有点不对。

我猜你的第二次尝试失败了,因为斜线 (/) 而不是反斜线 ()。

此外,我认为获取您的路径可能会导致不正确的结果。如果您的代码位于程序集缓存中的 DLL 中,您将获得程序集缓存的路径,而不是应用程序的位置。也许你应该考虑 GetEntryAssembly.

尝试使用 Path.Combine(...) 将动态路径与文件名结合起来,如下所示:

string connectionString = 
    @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" +
    System.IO.Path.Combine(
        System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().GetName().CodeBase), 
        "MyDatabase.mdf") + 
    @";Integrated Security = True;"