这是我第一次尝试使用代码优先技术在MVC3中完全使用.NET。 我已经通过网络平台安装了VS2010(10.0.3)和MVC3,.NET 4。然后我安装了MySQL .NET连接器6.4.3。然后我继续在服务器资源管理器中设置数据连接,这似乎工作正常。我使用MySQL网站配置配置了网站,您可以在web.config中看到下面的配置设置。
然后使用Scott Hanselman的视频教程(http://www.asp.net/mvc/videos/5-minute-introduction-to-aspnet-mvc)我创建了一个没有ICollections的模型(团队\播放器)(只是为了让它更简单),并使用视频中的MVC Scaffolding创建控制器例如,它反过来创建了视图。
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; }
}
登陆家庭\关于页面很好但是当访问团队页面时,我收到此错误:
建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。 (提供者:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接) 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中的起源位置的更多信息。
异常详细信息:System.Data.SqlClient.SqlException:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。 (提供者:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接) 下面的完整堆栈跟踪,它还提到它的ProviderManifestToken错误。
现在我知道连接(至少会话连接)正在工作,因为使用网络监视器我可以看到在端口3306上进行的呼叫设置&我第一次访问页面时锁定我的会话但我没有看到任何对MVC模型创建查询的引用。
在我看来,这只是连接器选择中的一个简单错误(其中使用SQL而不是mysql),但因为这是所有自动生成的代码我真的没有任何地方(我知道)我可以把它改成mysql。我网站中的每个文件都引用了mysql,所以我不确定是怎么回事。我在网上找到的任何英特尔引用了mySQL网站配置设置,这似乎很好(它甚至创建了my_aspnet_ *表)
我尝试了什么:
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>
这是完整的堆栈跟踪:
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
那么有谁知道如何配置MVC以使用正确的连接器并查询MySQL?
答案 0 :(得分:1)
您的代码中应该有一个继承自DbContext
的类,类似于以下内容:
public class SuperDatabaseContext : DbContext
{
public DbSet<player> Players { get; set; }
public DbSet<team> Teams { get; set; }
}
link you provided的含义是,您的类(在本例中为“SuperDatabaseContext”)应与Web.Config中ConnectionString的name
匹配。 e.g。
<add name="SuperDatabaseContext" connectionString="password=supersecrete;User Id=MyUsername;database=myDBName;server=SERVERLOCATIONASDOMAINNAM;" providerName="MySql.Data.MySqlClient" />
可能有用的其他参考资料:
另一方面注意:只需仔细检查您的连接字符串即可。我通常会得到那条消息,因为我是一个白痴,并没有在服务器名称中拼写一些东西.. :))
答案 1 :(得分:0)
有时这个问题也会因为sslmode而出现,对我来说,解决方法是将sslmode = None添加到连接字符串
我必须对来自
的连接字符串进行一些小改动<add name="Connection" connectionString="Server=SOMEHOST;Database=DB;Uid=USR1;Pwd=PASS1;" providerName="MySql.Data.MySqlClient" />
到
<add name="Connection" connectionString="Server=SOMEHOST;Database=DB;Uid=USR1;Pwd=PASS1;sslmode=None;" providerName="MySql.Data.MySqlClient" />