MVC 5 中的 System.Data.Entity.Core.ProviderIncompatible 异常 [英] System.Data.Entity.Core.ProviderIncompatible Exception in MVC 5

查看:28
本文介绍了MVC 5 中的 System.Data.Entity.Core.ProviderIncompatible 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating an ASP.NET Web Application in mvc5 and i made a model class with a controller. My application is running but when i want to access my moviescontroller in url like localhost:1234/Movies it generates an exception in my MoviesController.cs file

我使用的连接字符串是

<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"的异常,但未在用户代码中处理

An exception of type 'System.Data.Entity.Core.ProviderIncompatibleException' occurred in EntityFramework.dll but was not handled in user code

附加信息:从数据库获取提供者信息时出错.这可能是由实体框架使用不正确的连接字符串引起的.详细检查内部异常,确保连接字符串正确.

Additional information: 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.

内部异常详细信息:

    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 JoshiWebsitesMvcMovieMvcMovieControllersMoviesController.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 类是:

My DbContext class is:

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>

推荐答案

请使用 教程:

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

您对用户 sa 的身份验证可能有问题.

It is likely a problem with your authentication with the user sa.

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

I have just installed VS 2013 on my DevVM (Server 2008R2) I created an Asp.Net MVC 5 project and used nuget to add Entity Framework to the project. After this I created the models and added the connectionstring to the web.config Then I clicked controlles -> add -> scaffold, choose the model data context and name, hit add and then run the project. Works like a charm. All CRUD functionality is working.

这篇关于MVC 5 中的 System.Data.Entity.Core.ProviderIncompatible 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆