【问题标题】:Can't connect to MDF file无法连接到 MDF 文件
【发布时间】:2015-12-11 16:56:25
【问题描述】:

我无法使用以下代码连接到现有的 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.)

【问题讨论】:

  • 看起来您的 sql server 实例可能没有运行。您是否验证该服务正在运行?

标签: c# wpf database-connection


【解决方案1】:

这很有趣,不久前我也遇到过同样的问题。你说不管你怎么试都不行。不过,你在某个地方有一个错字。这是我的旧的:

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。我有问题。如果您遇到一些版本或兼容性问题,可能就是这样。

此外,我的代码中的“环境”有所改变,并将数据库用作实体框架的项目项。通过这种方式,Visual Studio 会生成连接字符串。在这里,我在一个配置文件中找到了它:

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

【讨论】:

    猜你喜欢
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多