指定的 LocalDB 实例不存在

LocalDB instance specified does not exist

我正在尝试使用 EntityFramework 6 在 SQL Server 2015 Express 中构建一个 ASP.NET MVC 5 Web 应用程序,但是当我调试应用程序并转到数据库所在的页面时需要我得到以下错误。

System.Data.SqlClient.SqlException was unhandled by user code ErrorCode=-2146232060 HResult=-2146232060 LineNumber=0 Message=Error relacionado con la red o específico de la instancia mientras se >establecía una conexión con el servidor SQL Server. No se encontró el servidor >o éste no estaba accesible. Compruebe que el nombre de la instancia es correcto >y que SQL Server está configurado para admitir conexiones remotas. (provider: >SQL Network Interfaces, error: 50 - Se produjo un error de Local Database >Runtime. La instancia de LocalDB especificada no existe.)

此错误提到存在远程连接问题,但这不可能,因为我在本地。 然后我收到以下错误:发生 localDB 实例本地数据库运行时错误。指定的 LocalDB 实例不存在。

堆栈跟踪:

    en System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
       en System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
       en System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
       en System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
       en System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
       en System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
       en System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
       en System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
       en System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
       en System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
       en System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
       en System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
       en System.Data.SqlClient.SqlConnection.Open()
       en System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
       en System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
       en System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
       en System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()
       en System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
       en System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
       en System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
       en System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
       en System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
       en System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
       en System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
       en System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
       en System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
       en System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
       en System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
       en System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
       en System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
       en System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
       en System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
       en System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
       en System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
       en System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
       en System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
       en System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
       en System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
       en System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
       en System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
       en System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       en System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       en System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
       en System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
       en System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       en System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       en WebApplication10.Controllers.AlbumsController.Index() en C:\Users\Develop2\Documents\Visual Studio 2015\Projects\WebApplication10\WebApplication10\Controllers\AlbumsController.cs:línea 20
       en lambda_method(Closure , ControllerBase , Object[] )
       en System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       en System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       en System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       en System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
       en System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
       en System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
       en System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       en System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
       en System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()

编辑
我的连接字符串如下所示:

 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication10-20151208105118.mdf;Initial Catalog=aspnet-WebApplication10-20151208105118;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="WebApplication10Context" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=WebApplication10Context-20151208105514; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|WebApplication10Context-20151208105514.mdf" providerName="System.Data.SqlClient" />
  </connectionStrings>

编辑 2

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="v11.0" />  
    </parameters>
     </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

应该是什么问题?

解决方案

正如 Cigano Morrison 所建议的,问题是缺少 localDB 实例,因此我不得不 运行 在命令行中执行以下命令 sqllocaldb c MSSQLLocalDB 11.0

首先,检查您的项目是否在 App_Data 文件夹中有文件 aspnet-WebApplication10-20151208105118.mdfWebApplication10Context-20151208105514.mdf(通常,它们不是解决方案的一部分。

其次,尝试用(LocalDb)\v11.0替换(LocalDb)\MSSQLLocalDB

第三,第二个连接字符串中缺少一个反斜杠:

<add name="WebApplication10Context" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=WebApplication10Context-20151208105514; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|\WebApplication10Context-20151208105514.mdf" providerName="System.Data.SqlClient" />

第四,检查您是否安装了 SQL 具有高级功能的服务器,其中包括 LocalDB。


要创建新的数据库文件,请右键单击 App_Data 文件夹 > 添加 > 新项目...

如果您使用的是 LocalDB,您实际上可以使用 Microsoft 的命令行工具来查看您的实例、它们的端点并根据需要启动和停止实例。您还可以使用 SQL 服务器管理工​​作室连接到 Visual Studio 之外的 LocalDB 实例,以便在更适合 SQL 操作的环境中工作。我在我的博客 post 此处 http://www.nikgupta.net/2015/12/connect-localdb-from-management-studio/

中详细介绍了这一切

只需使用此 cmd 命令创建实例

sqllocaldb create "MSSQLLocalDB"

或者默认情况下,sqllocaldb 附带一个实例,它是 v11 或 v12,遵循您的 sqlserver 版本,如果您要使用它,只需将 (localdb)\MSSQLLocalDB 替换为 (localdb)\v11