MYSQ & MVC3 SQL connection error \\ ProviderManif

2019-07-10 04:49发布

问题:

This is my first time attempting full usage of mysql in .NET with MVC3, using code first technology. I have installed VS2010 (10.0.3), and MVC3, .NET 4 via web platform. I then installed MySQL .NET connector 6.4.3 . I then proceeded to setup a Data Connection in Server Explorer, and that seems to work fine. I configured the site using MySQL Website Configuration, and you can see the config settings below in the web.config.

Then using Scott Hanselman's vid tutorial (http://www.asp.net/mvc/videos/5-minute-introduction-to-aspnet-mvc) I created a model (team\player) without the ICollections (just to keep it that much simpler), and created the controller using the MVC Scaffolding as in the video example , which in turn created the views.

public class team
    {
        public int teamId { get; set; }
        public string teamName { get; set; }

    }
    public class player
    {
        public int PlayerID { get; set; }
        public string PlayerName { get; set; }
    }

Landing on the home\about pages are fine but when accessing the Team page, I get this error:

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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) Full Stack Trace below where it also mentions that its a ProviderManifestToken error.

Now I know the connections (at least the session connection) is working because using network monitor I can see the calls being made on port 3306 to set & lock my session when I first access the page but I don't see any reference to the MVC model creation queries.

It seems to me that this just a simple error in connector selection (where its using SQL instead of mysql), but because this is all auto generated code I really don't have anywhere (that I know of) that I can change it to mysql. Every file in my site, makes references to mysql so I am not sure what is going on. Any intel I find online references the mySQL Website Configuration setup, which seems to be just fine (it even created the my_aspnet_* tables)

What I have tried:

  • removed session state from mysql
  • removed any reference to local database server
  • ensure connectivity, security, and communication is working
  • searched through the solution to see if there was anywhere that SQL Server was referenced.

Web.config

<?xml version="1.0"?>
<configuration>
  <connectionStrings>

    <remove name="LocalMySqlServer" />
    <add name="LocalMySqlServer" connectionString="password=supersecrete;User Id=MyUsername;database=myDBName;server=SERVERLOCATIONASDOMAINNAM;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <sessionState mode="Custom" cookieless="true" regenerateExpiredSessionId="true" customProvider="MySqlSessionStateProvider">
      <providers>
        <add name="MySqlSessionStateProvider" type="MySql.Web.SessionState.MySqlSessionStateStore, MySql.Web, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="Session" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" />
      </providers>
    </sessionState>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <membership defaultProvider="MySQLMembershipProvider">
      <providers>
        <clear />
                <remove name="MySQLMembershipProvider" />
        <add name="MySQLMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="Membership" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" enablePasswordRetrieval="False" enablePasswordReset="True" requiresQuestionAndAnswer="True" requiresUniqueEmail="False" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
      </providers>
    </membership>
    <profile defaultProvider="MySQLProfileProvider">
      <providers>
        <clear />

        <remove name="MySQLProfileProvider" />
        <add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="Profiles" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="False" autogenerateschema="True" />
      </providers>
    </profile>
    <roleManager enabled="false" defaultProvider="MySQLRoleProvider">
      <providers>
        <clear />

        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
        <remove name="MySQLRoleProvider" />
        <add name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.4.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="Roles" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="False" autogenerateschema="True" />
      </providers>
    </roleManager>
    <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.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Here is the full stack trace:

Stack Trace:

[SqlException (0x80131904): 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5050218
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) +341
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) +129
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +239
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +195
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +232
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +33
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +524
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
   System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +479
   System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +108
   System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +126
   System.Data.SqlClient.SqlConnection.Open() +125
   System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +85
   System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +349
   System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +265
   System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +34

[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
   System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +163
   System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +40
   System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +157
   System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +51
   System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +117
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +407
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +17
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +62
   System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +15
   System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +40
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
   MVC3Learning.Controllers.TeamController.Index() in D:\Visual Studio Projects\MVCLearning\MVC3Learning\Controllers\TeamController.cs:21
   lambda_method(Closure , ControllerBase , Object[] ) +62
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8920029
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

So does anyone know how I can configure MVC to use the correct connector and query MySQL?

回答1:

You should have a class within your code that is inheriting from the DbContext, something along the lines of:

public class SuperDatabaseContext : DbContext
{
    public DbSet<player> Players { get; set; }
    public DbSet<team> Teams { get; set; }
}

What the link you provided means, is that your class (in this case 'SuperDatabaseContext') should match the name of your ConnectionString in Web.Config. e.g.

<add name="SuperDatabaseContext" connectionString="password=supersecrete;User Id=MyUsername;database=myDBName;server=SERVERLOCATIONASDOMAINNAM;" providerName="MySql.Data.MySqlClient" />

Additional references that may be of use:

  • Scott Hanselman's blog post on EF4 Code First (though, it's CTP4).
  • Jon Galloway's talk about using with an existing DB (has comments on specifying connection string names)
  • Obligatory reference to Gu post.

On another side note: Just double check your connection string. I get that message normally because I'm an idiot and didn't spell something right in the server name etc.. :)



回答2:

Sometimes this issue arises because of sslmode as well, For me the solution was to add sslmode=None to connection string

I had to make a small change to my connection string from

<add name="Connection" connectionString="Server=SOMEHOST;Database=DB;Uid=USR1;Pwd=PASS1;" providerName="MySql.Data.MySqlClient" />

to

<add name="Connection" connectionString="Server=SOMEHOST;Database=DB;Uid=USR1;Pwd=PASS1;sslmode=None;" providerName="MySql.Data.MySqlClient" />