【问题标题】:Cannot attach the file as database / The underlying provider failed on Open无法将文件附加为数据库/基础提供程序在打开时失败
【发布时间】:2013-12-29 00:42:59
【问题描述】:

我有一个使用实体框架的 MVC3 应用程序。我已经有大约一年没有使用这个应用程序了。最近,我在一台新 PC 上打开它并尝试在调试模式下运行并在调试中点击以下异常/堆栈跟踪。主要的例外似乎是“无法将文件附加为数据库”和“底层提供程序在打开时失败”。我在堆栈溢出时搜索了这些错误,我发现的答案似乎与这种情况不匹配。例如,“无法将文件附加为数据库”的答案之一表明旧版本的数据库可能位于本地数据库上,但是当我浏览到 localdb 时,我在本地数据库中看不到任何数据库在视觉工作室。

我正在寻找有关接下来要调查什么以解决此问题的指导。有什么建议吗?

实际失败的代码是:

            var currentHunt = (from ph in this.repo.GetAllPuzzleHunts()
                           orderby ph.PuzzleHuntId descending
                           select ph).FirstOrDefault();

这是网络应用第一次尝试通过实体框架从数据库中获取数据。

FWIW 这台机器有 Entity Framework 6.0,我使用的是 Visual Studio 2012。

异常/堆栈跟踪如下:

System.Data.DataException was unhandled by user code
  HResult=-2146233087
  Message=An exception occurred while initializing the database. See the InnerException for details.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
       at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
       at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
       at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
       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.Linq.Buffer`1..ctor(IEnumerable`1 source)
       at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__0.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
       at GutolMvcApp.Controllers.HomeController.Index() in c:\Users\jordanat\Documents\Visual Studio 2012\Projects\Gutol\Gutol\GutolMvcApp\Controllers\HomeController.cs:line 25
       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.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
       at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
  InnerException: System.Data.Entity.Core.EntityException
       HResult=-2146233087
       Message=The underlying provider failed on Open.
       Source=EntityFramework
       StackTrace:
            at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
            at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
            at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
            at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
            at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
            at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
            at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
            at System.Lazy`1.CreateValue()
            at System.Lazy`1.LazyInitValue()
            at System.Lazy`1.get_Value()
            at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
            at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
            at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)
            at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
            at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
            at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
            at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
            at System.Data.Entity.Internal.EdmMetadataRepository.QueryForModelHash(Func`2 createContext)
            at System.Data.Entity.Internal.InternalContext.QueryForModelHash()
            at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata)
            at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata)
            at System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata)
            at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
            at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse`1.<CreateInitializationAction>b__d()
            at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
       InnerException: System.Data.SqlClient.SqlException
            HResult=-2146232060
            Message=Cannot attach the file 'C:\Users\...\Visual Studio 2012\Projects\Gutol\Gutol\GutolMvcApp\App_Data\PuzzleCollateral.mdf' as database 'PuzzleCollateral'.

感谢您的帮助!

【问题讨论】:

    标签: asp.net-mvc-3 entity-framework visual-studio-debugging localdb


    【解决方案1】:

    试试这个方法:

    https://stackoverflow.com/a/16339164/1390999

    在您的下方打开“VisualStudio 的开发人员命令提示符” 开始/程序菜单。运行以下命令:

    sqllocaldb.exe 停止 v11.0

    sqllocaldb.exe 删除 v11.0

    之后,尝试启动您的 MVC 应用程序

    【讨论】:

      【解决方案2】:

      检查您的连接字符串。如果您使用的是新计算机,则可能需要对其进行一些更改或在防火墙中打开一个端口。

      获取正确连接字符串的一种简单方法是连接到数据库服务器并查看属性。

      1. 打开 SQL Server 对象资源管理器(查看 > SQL Server 对象资源管理器)
      2. 连接数据库服务器(点击“连接服务器”输入“(LocalDB)\v11.0”)
      3. 右键单击相应的数据库并选择“属性”
      4. 查看连接字符串

      【讨论】:

      • 感谢您的建议。我查看了本指南以获取连接字符串:creating a connection string。我编写了以下连接字符串并将其添加到我的项目的 web.config 文件中:&lt;add name="PuzzleCollateralContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\PuzzleCollateral.mdf;Integrated Security=True" providerName="System.Data.SqlClient" /&gt; 即使使用新的连接字符串,我也得到了相同的异常。我更新了 Web.config)。
      • 我在我的一个项目中使用 localdb。我的连接字符串不包含任何关于AttachDbFilename 的内容,但我看到他们在教程中提到了它。试试&lt;add name="PuzzleCollateralContext" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=PuzzleCollateral;Int‌​egrated Security=True" providerName="System.Data.SqlClient" /&gt;
      • 再次,我得到了同样的错误。我可以在运行时做些什么来查看它使用了正确的连接字符串吗?我发现异常说:{"Cannot attach the file 'C:\\Users\\&lt;snip&gt;\\App_Data\\PuzzleCollateral.mdf' as database 'PuzzleCollateral'."} 我不知道它在哪里推断出 PuzzleCollat​​eral 的名称。
      • 您是否尝试按照我在编辑后的答案中提到的那样连接到数据库?
      • 是的,我试过了。 SSOE 报告的 localdb 连接字符串为:Data Source=(localdb)\Projects;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False。在 Web.Config 中使用这个连接字符串我得到了相同的结果。看到我似乎无法对运行时行为进行任何更改,我想我可能在错误的位置编辑连接字符串,或者它没有使用我认为应该使用的字符串。那可能吗?我正在编辑 MVC 项目中的 web.config 文件。
      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多