SQL 服务器 LocalDB 根本无法创建数据库

SQL Server LocalDB simply failing to create DB

这是我的完整示例:

var builder = new SqlConnectionStringBuilder();
builder.DataSource = "(localdb)\v11.0";
builder.IntegratedSecurity = true;
builder.AttachDBFilename = "test.mdf";
builder.InitialCatalog = "test";
builder.ConnectTimeout = 60;

var connStr = builder.ToString();

using (var conn = new SqlConnection(connStr))
{
    conn.Open();
}

异常:

System.Data.SqlClient.SqlException (0x80131904): Cannot attach the file 'test.mdf' as database 'test'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
ClientConnectionId:6ea99bb4-5703-4354-84f3-cfc5bcd8c045
Error Number:1832,State:1,Class:14

如果我注释掉 AttachDBFilename 部分,我得到:

Cannot open database "test" requested by the login. The login failed.

如果我注释掉 InitialCatalog 部分,我得到:

An attempt to attach an auto-named database for file test.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

我是 运行 普通用户,如果我使用 Path.GetTempPath() 指定数据路径,我会得到完全相同的错误,即我有权访问数据位置。

不存在 test.mdf 文件,也没有 test 数据库。我可以随心所欲地更改文件名和数据库名,并获得完全相同的消息。

如果我使用 sqllocaldb 工具来 stopdelete v11.0 实例,那么 第一次 时间运行上面的代码,我得到:

Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement. This could be because the pre-login handshake failed or the server was unable to respond back in time. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=3274; handshake=1;

(这几乎立即发生,即它不会用完我在连接字符串中设置的 60 秒连接超时)

如果我重新启动计算机然后 运行 代码,我会看到相同的结果。

之后,我得到上面的错误,每次都一样。

我不确定还能尝试什么!

好的,这是交易:

LocalDB 实际上不会自动创建数据库。只是大多数示例都是 Entity Framework 个,在很多配置中会创建缺失的数据库。

EF 实际上非常聪明,它将检测连接字符串中的 AttachDBFilename 值以构建自定义 CREATE DATABASE 命令,以及正确的 data/log 文件路径指定值。它将尝试使用指定的连接字符串,如果失败,它将调整连接字符串以连接到 master 数据库并发出 CREATE DATABASE。最后,我也是这么做的。

顺便说一句,我实际上在我的主要示例中使用了 EF。我问题中的代码是一个很好的测试用例,但我被困了很长时间,得到与我在此处概述的完全相同的异常,即使在 "auto-create-if-missing" 配置模式下使用 EF 也是如此。这是因为我打开了异常中断,同时关闭了“仅我的代码”,即我看到了 EF 内部异常。