介尘部落

文学|音乐|休闲娱乐|计算机技术|地球科学|社会学——知识成就命运


DotNet5.0 连接MySql配置方法

原来的aspnetcore 3.1项目升级到net5.0之后,关于mysql在entityframework下的链接使用竟然出现报错。

一开始的报错是

An unhandled exception has occurred while executing the request.
System.TypeLoadException: Method 'Create' in type 'Pomelo.EntityFrameworkCore.MySql.Query.ExpressionVisitors.Internal.MySqlSqlTranslatingExpressionVisitorFactory' from assembly 'Pomelo.EntityFrameworkCore.MySql, Version=3.1.1.0, Culture=neutral, PublicKeyToken=2cc498582444921b' does not have an implementation.
   at Microsoft.Extensions.DependencyInjection.MySqlServiceCollectionExtensions.AddEntityFrameworkMySql(IServiceCollection serviceCollection)
   at Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal.MySqlOptionsExtension.ApplyServices(IServiceCollection services)

那自然是dotnet5.0跟mysql的提供程序之间出了不匹配的问题。在nuget中查询Pomelo.EntityFrameworkCore.MySql的版本只到3.2.4,还没有dotnet5.0的相应版本。然而事实上,Pomelo.EntityFrameworkCore.MySql 已经发布了预览版的dotnet5.0的支持。只需在nuget搜索的时候选中“包括预览版”即可搜索到Pomelo.EntityFrameworkCore.MySql 的预览版本 5.0.0-alpha.2 。命令行安装如下:

dotnet add package Pomelo.EntityFrameworkCore.MySql --version 5.0.0-alpha.2

安装了5.0.0-alpha.2包后,原来的ef mysql连接配置发生了报错,已经不存在如下的配置方式:

services.AddDbContext<MySqlContext>(options =>options.UseMySql(Configuration.GetConnectionString("OnlineCon")));

查询Pomelo.EntityFrameworkCore.MySql的github文档后,了解到最新的连接配置发生了变化。最新的方法是下面这样:

// Replace "YourDbContext" with the name of your own DbContext derived class.
services.AddDbContextPool<YourDbContext>(
    dbContextOptions => dbContextOptions
        .UseMySql(
            // Replace with your connection string.
            "server=localhost;user=root;password=1234;database=ef",
            // Replace with your server version and type.
            // For common usages, see pull request #1233.
            new MySqlServerVersion(new Version(8, 0, 21)), // use MariaDbServerVersion for MariaDB
            mySqlOptions => mySqlOptions
                .CharSetBehavior(CharSetBehavior.NeverAppend))
        // Everything from this point on is optional but helps with debugging.
        .EnableSensitiveDataLogging()
        .EnableDetailedErrors();
));

也就是在UseMySql中增加了一个MySqlServerVersion的配置。将这个值设置为了服务器上MySql的版本,重新发布了Web应用,错误已经解决了。

阅读全文
公众号-介尘阅读时光
赞赏支持

0 Responses to “DotNet5.0 连接MySql配置方法”

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)