【问题标题】:Can't connect to Mysql from asp.net api无法从 asp.net api 连接到 Mysql
【发布时间】:2021-06-03 23:45:33
【问题描述】:

我很难连接到 mySQL 服务器...每次我尝试连接时,都会收到“内部连接致命错误”消息。

这是我的代码的一些部分:
启动.cs:
{
    services.AddDbContext<MyAppContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));  

    services.AddControllers();
}

appsettings.json:

"ConnectionStrings": 
  {
    "MyConnectionString" : "server=localhost,3306;database=myDB;user=root;password="
  }

我的 csproj 文件:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.3" />
  </ItemGroup>


</Project>

对于 ConnectionStrings 部分,我尝试了这个:

"ConnectionStrings": 
  {
    "MyConnectionString" : "server=localhost;database=myDB;user=root;password="
  }

但这一次,我收到了这条消息:“在建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。找不到服务器或无法访问该服务器。验证实例名称是否正确,并且SQL Server 配置为允许远程连接。(提供程序:命名管道提供程序,错误:40 - 无法打开与 SQL Server 的连接)"
供您参考,我的 sqlserver 使用 WAMP 运行。

我希望我很清楚,如果您提供更多信息或模式代码,请不要犹豫。

提前致谢

【问题讨论】:

  • 正在使用 Mysql 还是 SQLServer?您的代码似乎是为 SQL 服务器编写的,但您在标题中提到了 Mysql。

标签: c# mysql asp.net-core wamp


【解决方案1】:

我认为你必须下载 MySql.Data.EntityFrameworkCore 而不是 Microsoft.EntityFrameworkCore.SqlServer。

【讨论】:

  • 你在 dotnet core 中吗?
  • 是的,我在.net core中
【解决方案2】:

您可以使用MySql驱动连接MySql服务器。对于 EF Core,您必须下载此 Nuget Package

.Net 3.1版本,下载Pomelo Nuget包后可以使用以下代码;

        services.AddDbContext<MyAppContext>(opt =>
        {
            opt.UseMySql(configuration.GetConnectionString("MySqlConnection"));

        });

在.Net 5 版本中;

        string connectionString =configuration.GetConnectionString("MySqlConnection")
        services.AddDbContext<MyAppContext>(opt =>
        {
            opt.UseMySql(connectionString,
                         ServerVersion.AutoDetect(connectionString)));

        });

【讨论】:

  • 感谢您的回答。它现在似乎可以工作,但我还有另一个问题......我试图做dotnet ef migrations remove,但我现在有这个错误:方法'Create' in type 'Pomelo.EntityFrameworkCore.MySql.Query.ExpressionVisitors.Internal.MySqlSqlTranslatingExpressionVisitorFactory ' 来自程序集 'Pomelo.EntityFrameworkCore.MySql, Version=3.2.4.0, Culture=neutral, PublicKeyToken=2cc498582444921b' 没有实现。
  • 我认为这与包版本不兼容有关。您的 EF Core 版本和 Pomelo 版本应该兼容。但我不确定。看看并通知我:)
  • 我的EF版本是5.0.3
  • 所以,您可以使用 Pomelo 5.0.0-alpha.1 或 Pomelo 5.0.0-alpha.2 版本。版本 3.2.4.0 兼容 .net core 3.x
  • 好的,我做到了,但我还有另一个问题......对不起,我很陌生。现在我有 错误 cs1503 参数 2 无法从“字符串”转换为“Microsoft.EntityFrameworkCore.ServerVersion”。我试过这个opt.UseMySql(configuration.GetConnectionString("MySqlConnection"), new MySqlServerVersion(new Version(8, 0, 21))); 但它不起作用
【解决方案3】:

dotnet core: nuget - Microsoft.EntityFrameworkCore.Design, Microsoft.EntityFrameworkCore.SqlServer 那么你会很好。从您的项目中删除所有其他实体框架包

public void ConfigureServices(IServiceCollection 服务) { services.AddControllersWithViews();

        var connectionString =Configuration.GetConnectionString("MYDB_DbCoreConnectionString");
         services.AddDbContext<MYDContext>(options1 => options1.UseSqlServer(connectionString)) ;

        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        // configure DI for application services
        services.AddScoped<IUserService, UserService>();
        

}

【讨论】:

    猜你喜欢
    • 2014-03-15
    • 2022-01-19
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多