无法连接到 MDF 文件

Can't connect to MDF file

我无法使用以下代码连接到现有的 MDF 文件:

conn = new SqlConnection("Data Source=(LocalDB)\v11.0;" +
    "Integrated Security=True;" +
    "AttachDbFilename=" + Path.GetFullPath("Database.mdf") + ";");
conn.Open();

无论我尝试什么,我都收到以下错误:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.)

很有趣,我不久前也遇到过同样的问题。你说无论你尝试什么都不行。不过,您在某处有错字。这是我的旧版本:

public const string ssqlconnectionstring = @"Data Source=(LocalDB)\v11.0;" +
    @"AttachDbFilename=C:\MyFilePath\MyDBFile.mdf;" +
    @"Integrated Security=True;" +
    @"MultipleActiveResultSets=True;" +
    @"User Instance=False";

此外,您可以使用

"(LocalDB)\MSSQLLocalDB";

而不是 \v11.0。我有问题。如果遇到版本或兼容性问题,可能就是这样。

此外,"environment" 在我的代码中做了一些更改,将数据库用作 Entity Framework 的项目项。这样 Visual Studio 生成连接字符串。在这里,我在配置文件中找到了它:

<Value Profile="(Default)">Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\MyFilePath\MyDBFile.mdf;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework</Value>