发布 C# 后的本地数据库

Local Database after publishing C#

我正在努力使我的程序在发布后可以拥有一个本地数据库。现在我想让它工作,这样我就可以在任何计算机上安装,所以我必须更改我的连接字符串,但我似乎无法弄清楚要将其更改为这是我现在拥有的连接字符串

string constring = "Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = \"C:\Barcode\Application Files\Barcode Scanning_1_0_0_0\BarcodeDB.mdf\"; Integrated Security = True";

在发布之前,我进入了 applicationfiles 并确保包含 BarcodeDB.mdf,但据我所见,它在我发布后变为 BarcodeDB.mdf.deploy。

我还进入了先决条件并添加了

SQL Server 2012 Express LocalDB

当我尝试 运行 已发布的程序或调试器使用我现在拥有的代码时,出现错误:

An attempt to attach an auto-named database for file C:\Barcode\Application Files\Barcode Scanning_1_0_0_0\BarcodeDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share

我想我需要使用:

| DataDirectory |

但是我对这一切都是陌生的,所以我似乎无法弄清楚如何使用它,即使搜索了它,所以我将不胜感激,如果有人能友好地解释一下我应该怎么做正在使用 DataDirectory,或者如果我错了应该使用其他东西。

如果我试图更好地解决这个问题,我也很抱歉

最好的问候汉内斯。

编辑 1:这是我尝试连接和使用数据库的代码

        string constring = $"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\Application Files\Barcode Scanning_1_0_0_0\BarcodeDB.mdf\"; Integrated Security = True";
        string Query = "SELECT Name FROM Products ORDER BY EDate;";
        SqlConnection conDataBase = new SqlConnection(constring);
        SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
        SqlDataReader myReader;
        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();
            while (myReader.Read())
            {

                string sName = myReader.GetString(myReader.GetOrdinal("Name"));
                cbxProducts.Items.Add(sName);
                cbxProducts.Sorted = false;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

好的,我假设您的项目是 Windows Forms 或 WPF 项目,如果不是,请告诉我。

您的问题是您正在硬编码数据库文件的路径,该文件可能不存在或者您的进程无法访问它的位置。您发现 | DataDirectory | 是在 Web 项目中使用的 Web.Config 文件,该文件将映射到 App_Data 文件夹。

在您的情况下,您必须使用您自己的应用程序可执行路径构建连接字符串。试试这个代码:

//WPF:
string constring = $"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = \"{System.Reflection.Assembly.GetExecutingAssembly().Location}\BarcodeDB.mdf\"; Integrated Security = True";

//Windows Forms:
string constring = $"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\BarcodeDB.mdf\"; Integrated Security = True";
        string constring = $"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + Directory.GetCurrentDirectory().ToString() + "\BarcodeDB.mdf;Integrated Security=True";

这帮我修好了