无法从“字符串”转换为“Microsoft.EntityFrameworkCore.ServerVersion”

The*_*ain 4 c# mysql entity-framework-core

我正在使用 C# 并且有一个错误: Argument 2: cannot convert from 'string' to 'Microsoft.EntityFrameworkCore.ServerVersion'

    using Microsoft.EntityFrameworkCore;
    using System;
    
    namespace Infrastructure
    {
        public class BotContext : DbContext 
        {
            public DbSet<Server> Servers { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder options)
                => options.UseMySql("server=localhost;user=root;port=3306;Connect Timeout=5;");
    
            public class Server
            {
                public ulong Id { get; set; }
                public string Prefix { get; set; }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

ehs*_*_33 11

显然,新版本Pomelo需要更多的论证。一个简单的解决方案是在startup.cs中添加一个空Version类,如下所示:

services.AddDbContext<ApplicationDB>(options =>
                   options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), new MySqlServerVersion(new Version())));
Run Code Online (Sandbox Code Playgroud)

更新 2022 .Net 6 现在我们没有startup.cs,所以将其添加到program.cs

string? connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataContext>(options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));


var app = builder.Build();
Run Code Online (Sandbox Code Playgroud)


The*_*ain 6

public class BotContext : DbContext 
{
    public DbSet<Server> Servers { get; set; }
    public BotContext()
    {
        Database.EnsureCreated();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseMySql(
            "server=localhost;user=root;port=3306;Connect Timeout=5;",
            new MySqlServerVersion(new Version(8, 0, 11))
        );
    }

    public class Server
    {
        public ulong Id { get; set; }
        public string Prefix { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该会有所帮助:https : //metanit.com/sharp/entityframeworkcore/7.2.php