【问题标题】:Cannot connect to database in MVC once SQL Server installed安装 SQL Server 后无法连接到 MVC 中的数据库
【发布时间】:2014-09-22 22:16:59
【问题描述】:

我正在浏览这个 Visual Studio 的 MVC 教程 - http://www.asp.net/mvc/tutorials/mvc-5/introduction/adding-a-model

顺便说一句,很棒的教程。但是当我最初制作这个电影应用程序时,一切正常。但是现在连接到数据库时出现此错误。

System.Data.Entity.Core.ProviderIncompatibleException was unhandled by user code HResult=-2146233087 Message=An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. 

我附上了下面的堆栈跟踪。

这是我在 Web.config 文件中使用的连接字符串(底部是我尝试连接的数据库)。

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20140922085615.mdf;Initial Catalog=aspnet-MvcMovie-20140922085615;Integrated Security=True"
  providerName="System.Data.SqlClient" />
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
  providerName="System.Data.SqlClient" />
</connectionStrings>

我想我知道问题的原因我只是不知道如何解决它。当我安装 Microsoft SQL Server 2014 时,这一切都失败了。当我在我的 mac 上的虚拟框下运行相同的程序时,它就可以工作了。所以问题不在于代码,我的 mac 没有安装 SQL Server。

如果有人可以提供帮助,我将不胜感激。请记住,我对编程有点陌生,因此我将不胜感激非常明确且易于遵循的说明/建议。

有些人在 cmets 中提到他们创建了一个 SQL 数据库并且工作正常,但我不知道在 Visual Studio 中做什么或如何执行此操作,也不知道我需要的连接字符串。如果有人能在这方面给我很好的指导,那就太好了!

Source=EntityFramework
 StackTrace:
   at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
   at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3 k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection)
   at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.Initialize()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MvcMovie.Controllers.MoviesController.Index() in c:\Users\basse_000\OneDrive\Documents\MVC\MvcMovie\MvcMovie\Controllers\MoviesController.cs:line 20
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()
  InnerException: System.Data.Entity.Core.ProviderIncompatibleException
   HResult=-2146233087
   Message=The provider did not return a ProviderManifestToken string.
   Source=EntityFramework
   StackTrace:
        at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
        at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
   InnerException: System.Data.SqlClient.SqlException
        HResult=-2146232060
        Message=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: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
        Source=.Net SqlClient Data Provider
        ErrorCode=-2146232060
        Class=20
        LineNumber=0
        Number=2
        Server=""
        State=0
        StackTrace:
             at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
             at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
             at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
             at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
             at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
             at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
             at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
             at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
             at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
             at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
             at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
             at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
             at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
             at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
             at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
             at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
             at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
             at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
             at System.Data.SqlClient.SqlConnection.Open()
             at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass2f.<UsingConnection>b__2d()
             at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
             at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
             at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
             at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
             at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
             at System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
             at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
        InnerException: System.ComponentModel.Win32Exception
             HResult=-2147467259
             Message=The system cannot find the file specified
             ErrorCode=-2147467259
             NativeErrorCode=2
             InnerException: 

【问题讨论】:

  • 您的连接字符串中是否缺少Database Name
  • 这是从教程中复制的,它适用于在我的 Mac 上运行的 Windows?

标签: sql-server asp.net-mvc asp.net-mvc-4 visual-studio-2012


【解决方案1】:

您是否都在 Visual Studio 中运行?还是mac visual studio和pc是已发布的版本?您收到错误是因为它可以找到这些文件之一

|DataDirectory|\aspnet-MvcMovie-20140922085615.mdf
|DataDirectory|\Movies.mdf

在 MVC 站点中 |DataDirectory|应该解析到站点根目录中的 App_Data 文件夹,因此您应该做的第一件事是检查这些文件是否存在。如果它们是您的 sql 服务器可能已经以某种方式重新配置了位置 - 我不确定。你可以使用

var actualDataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory");

找出它在哪里寻找并用类似这样的东西覆盖它

var path = Server.MapPath(@"\App_Data");
AppDomain.CurrentDomain.SetData(path, path);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多