ASP.NET Core5.0 MVC中 Pomelo.EntityFrameworkCore.MySql包在框架net5.0怎么连接数据库

ASP.NET Core5.0 MVC中 Pomelo.EntityFrameworkCore.MySql包在框架net5.0怎么连接数据库

appsettings.json

img

Startup.cs

img

里面的代码怎么写才能连接mysql

首先不论你使用什么支持MYSQL的nuget,你要先安装Microsoft.EntityFrameworkCore version 5.0.17。
创建好对应的DbContext, 例如:

public class MyDBContext : DbContext
{
    public MyDBContext(DbContextOptions<MyDBContext> options) : base(options)
    {
    }
    public DbSet<User> Users { get; set; }
}

然后安装MySql.EntityFrameworkCore version 5.0.13。 参考:

更改你的Startup.cs代码:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddDbContext<MyDBContext>(opt => opt.UseMySQL(Configuration.GetConnectionString("WebApplicationContext")));
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Replace with your connection string.
        var connectionString = "server=localhost;user=root;password=1234;database=ef";

        // Replace with your server version and type.
        // Use 'MariaDbServerVersion' for MariaDB.
        // Alternatively, use 'ServerVersion.AutoDetect(connectionString)'.
        // For common usages, see pull request #1233.
        var serverVersion = new MySqlServerVersion(new Version(8, 0, 27));

        // Replace 'YourDbContext' with the name of your own DbContext derived class.
        services.AddDbContext<YourDbContext>(
            dbContextOptions => dbContextOptions
                .UseMySql(connectionString, serverVersion)
                // The following three options help with debugging, but should
                // be changed or removed for production.
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors()
        );
    }
}

开源地址
https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql