MVC 5 中的 System.Data.Entity.Core.ProviderIncompatible 异常

Posted

技术标签:

【中文标题】MVC 5 中的 System.Data.Entity.Core.ProviderIncompatible 异常【英文标题】:System.Data.Entity.Core.ProviderIncompatible Exception in MVC 5 【发布时间】:2013-08-23 17:30:03 【问题描述】:

我正在 mvc5 中创建一个 ASP.NET Web 应用程序,并使用控制器创建了一个模型类。我的应用程序正在运行,但是当我想在 localhost:1234/Movies 之类的 url 中访问我的电影控制器时,它会在我的 MoviesController.cs 文件中生成一个异常

我使用的连接字符串是

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20130819083100.mdf;Initial Catalog=aspnet-MvcMovie-20130819083100;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <add name="MovieDBContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;User ID=sa; Password=password@123;" providerName="System.Data.SqlClient"/>
</connectionStrings>

产生这个异常的函数是

public ActionResult Index()

    return View(db.Movies.ToList());

编辑异常详情

EntityFramework.dll 中出现“System.Data.Entity.Core.ProviderIncompatibleException”类型的异常,但未在用户代码中处理

附加信息:从数据库获取提供程序信息时出错。这可能是由 Entity Framework 使用不正确的连接字符串引起的。检查内部异常以获取详细信息并确保连接字符串正确。

内部异常详情:

    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.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
       at System.Data.Entity.Infrastructure.DefaultManifestTokenService.GetProviderManifestToken(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 d:\Nimit Joshi\Websites\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: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)
            Source=.Net SqlClient Data Provider
            ErrorCode=-2146232060
            Class=20
            LineNumber=0
            Number=-1983577832
            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__DisplayClass2c.<UsingConnection>b__2a()
                 at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
                 at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 func)
                 at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action action)
                 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: 

我的 DbContext 类是:

public class MovieDBContext : DbContext

    public  DbSet<Movie> Movies  get; set; 
 

我的整个配置文件是:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20130819083100.mdf;Initial Catalog=aspnet-MvcMovie-20130819083100;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <add name="MovieDBContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=TempMovies;AttachDbFilename=|DataDirectory|\TempMovies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusivejavascriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="MvcMovie" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

【问题讨论】:

如果可能,请提供异常文本。 @Serv 我发布了我的异常详细信息...您可以查看... Serv 的意思是也提供内部异常,这就是详细信息将引导您发现问题的地方。正如消息所说:检查内部异常以获取详细信息! 您使用的是哪个连接? DefaultConnection 还是 MovieDBContext?您是否正在关注 www.asp.net 上的教程?如果异常没有提供足够的信息,则可能与重现问题有关 @Serv 是的,我正在关注该教程,并且我正在使用 MovieDBContext 作为连接。 【参考方案1】:

请使用tutorial:中提供的正确连接字符串

<add name="MovieDBContext" 
   connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" 
   providerName="System.Data.SqlClient" 
/> 

这可能是您对用户sa 的身份验证存在问题。

//更新

我刚刚在我的 DevVM (Server 2008R2) 上安装了 VS 2013 我创建了一个 Asp.Net MVC 5 项目并使用 nuget 将实体框架添加到项目中。 在此之后,我创建了模型并将连接字符串添加到 web.config 然后我点击了控制器 -> 添加 -> 脚手架,选择模型数据上下文和名称,点击添加,然后运行项目。奇迹般有效。所有 CRUD 功能都在工作。

【讨论】:

我第一次在我的 Web.Config 文件中使用了这个连接字符串,但是当我遇到这个异常时,我更改了我的连接字符串并提供了用户和密码。 我正在使用 Visual Studio 2013 预览版 请在开篇文章中提供您的 DbContext 类 我在开篇文章中发布了我的 DbContext 课程 我做过同样的事情,但上帝知道真正的问题是什么?【参考方案2】:

我的 LocalDB 已删除。我重新创建它,我的项目现在运行成功。谢谢大家对我的支持。

【讨论】:

如何重新创建 LocalDB ? 这是一个老问题,但@Nimit Joshi 你能告诉我如何重新创建 LocalDB。我和你的情况一样【参考方案3】:
> Here EmployeeDetail is a table name and Employee is a model name.  And
> ID,Branch,Salary and UID is a table field


  public ActionResult Index()
                
                    List<EmployeeDetail> employees = context.EmployeeDetails.ToList();
                    List<Employee> emp = new List<Employee>();
                    foreach(EmployeeDetail item in employees)
                    
                        emp.Add(new Employee
                            
                                ID=Convert.ToInt32(item.ID),
                                Branch=item.Branch,`enter code here`
                                Salary=Conve`enter code here`rt.ToInt32(item.Salary),
                                UID = Convert.ToInt32(item.ID),
                            );
                    
                    return View(emp);
                



>  view page code


    <div style="font-family:Arial">
        <h2>Index</h2>

        <ul>
            @foreach (var emp in Model)
            
                <li>
                    @Html.ActionLink(emp.Branch, "Details", new  id = emp.ID );
                </li>
            

        </ul>
    </div>

【讨论】:

【参考方案4】:

不要使用“.”定义数据库服务器。使用完整的机器名称

【讨论】:

拜托,你能解释一下原因吗?【参考方案5】:

我相信这是由 2 个连接字符串引起的……遇到了同样的问题,摆脱一个有帮助。

【讨论】:

【参考方案6】:

请注意,您可能还有一些 user.config 文件误入了您的应用程序拾取的路径中

C:\Users\USERNAME\AppData\Local\PROJECTNAME_vs_Url_a2dblg5lbsfkc1adurpcald1inggdlg1\

【讨论】:

以上是关于MVC 5 中的 System.Data.Entity.Core.ProviderIncompatible 异常的主要内容,如果未能解决你的问题,请参考以下文章

数据项目中的 MVC 5 HttpContext.User

MVC 5 视图中的@model 和 Model 是啥

参考视图文件夹中的 JavaScript 文件 - MVC 5

视图中的 MVC 5 枚举 - 隐藏单个元素

VS 2015 ASP.NET 4 MVC 5 中的打字稿 - 设置和选择的工作组合是啥?

如何在 MVC 5 中使用用户身份中的角色