web-dev-qa-db-fra.com

Exception System.Data.Entity.Core.ProviderIncompatible dans MVC 5

Je crée une application Web ASP.NET dans MVC5 et j'ai créé une classe de modèle avec un contrôleur. Mon application est en cours d'exécution, mais lorsque je souhaite accéder à mon contrôleur de films dans une URL telle que localhost: 1234/Movies, une exception est générée dans mon fichier MoviesController.cs.

La chaîne de connexion que j'utilise est 

<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>

Fonction qui génère cette exception est

public ActionResult Index()
{
    return View(db.Movies.ToList());
}

Modifier les détails de l'exception

Une exception de type 'System.Data.Entity.Core.ProviderIncompatibleException' s'est produite dans EntityFramework.dll mais n'a pas été gérée dans le code utilisateur.

Informations complémentaires: Une erreur s'est produite lors de l'obtention des informations sur le fournisseur à partir de la base de données. Cela peut être dû à Entity Framework utilisant une chaîne de connexion incorrecte. Vérifiez les exceptions internes pour plus de détails et assurez-vous que la chaîne de connexion est correcte.

Détails de l'exception interne:

    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: 

Ma classe DbContext est:

public class MovieDBContext : DbContext
{
    public  DbSet<Movie> Movies { get; set; }
 }

Mon fichier de configuration complet est:

<?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>
13
Nimit Joshi

veuillez utiliser la chaîne de connexion correcte fournie dans le didacticiel :

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

C'est probablement un problème d'authentification avec l'utilisateur sa.

//Mettre à jour

Je viens d'installer VS 2013 sur ma DevVM (Server 2008R2) J'ai créé un projet Asp.Net MVC 5 et utilisé nuget pour ajouter Entity Framework au projet . Après cela, j'ai créé les modèles et ajouté la chaîne de connexion à le web.config Ensuite, j'ai cliqué sur les commandes -> ajouter -> échafaudage, choisir le contexte et le nom des données du modèle, appuyer sur Ajouter, puis exécuter le projet. Fonctionne comme un charme. Toutes les fonctionnalités de CRUD fonctionnent.

3
Marco

Ma LocalDB a été supprimée. Je le recrée et mon projet fonctionne maintenant avec succès. Merci à tous de me soutenir.

1
Nimit Joshi
> 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>
1
Satyendra negi

Je crois que cela est causé par 2 chaînes de connexion ... eu le même problème et se débarrasser d'une aide.

0
stuartdotnet

ne pas utiliser "." définir le serveur de dbs. utiliser le nom complet de la machine

0
Aarif Saiyed

Veillez à ce que certains fichiers user.config se soient égarés dans le chemin d’être récupérés par votre application.

C:\Utilisateurs\NOMUTILISATEUR\AppData\Local\PROJECTNAME_vs_Url_a2dblg5lbsfkc1adurpcald1inggdlg1 \

0
Paul Farry