尝试读取数据库 C# 错误

Trying to read a database C# Errors

我正在尝试从我的 SQL 数据库中读取,但是我收到以下错误

System.Data.SqlClient.SqlException: 'An attempt to attach an auto-named database for file D:\Work Practise\Keepmefit\Keepmefit\App_Data\Keepmefit.Models.CardioDBssContext.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.'

我附上了下面的代码。我在我的代码上做了一些断点,异常来自 connection.Open();

我为此花了一整天的时间,并尝试了很多不同的方法,但似乎没有任何效果。任何反馈将不胜感激。

public class StrengthController : Controller
{
    private const string VV = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Work Practise\Keepmefit\Keepmefit\App_Data\Keepmefit.Models.CardioDBssContext.mdf;Integrated Security=True";
    // GET: Rep
    public ActionResult Index()
    {
       // SqlDataReader read = null;
        SqlConnection connection = new SqlConnection(VV);

        using (connection)
        {
            SqlCommand myCommand = new SqlCommand("SELECT * FROM Strength",
                                                connection);
            connection.Open();

            SqlDataReader read = myCommand.ExecuteReader();
            if (read.HasRows)
            {
                while (read.Read())
                {
                    Console.WriteLine("Working" + read["Id"].ToString());
                }
            }
            else
            {
                Console.WriteLine("nothing");
            }
            read.Close();
        }
        return View();

查看连接字符串中的双反斜杠。当您定义带有前导 'at' (@) 字符的字符串时,如下所示:

string VV = @"C:\some\file\path";

即所谓的verbatim string,反斜杠(\)字符对语言没有任何特殊意义。将它们加倍会得到一个确实有两个反斜杠的字符串,这可能会破坏您的文件路径。

在某些情况下,如果您只是将带有额外 \ 字符的路径发送到文件系统,您最终还是没问题,但对于这种情况,我怀疑额外的反斜杠会欺骗连接对象您正在尝试连接到文件共享路径(即:\server\share),这是不允许的。