Mysql

1、链接mysql

1、安装相关库
Pomelo.EntityFrameworkCore.MySql

这个库注意与EntityFrameworkCore相关的库版本要匹配,也不要跟其他数据库连接的包一起安装,比如Sqlite!!!

2、appsettings.json中配置数据库连接信息
添加ConnectionStrings

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "tarefasConnection": "server=localhost;port=3306;uid=root;pwd=password;database=database"
  },
  "AllowedHosts": "*"
}

3、在Program.cs中依赖注入容器中注册UserContext类

builder.Services.AddDbContext<UserContext>(opt =>
    {
        string connectionString = builder.Configuration.GetConnectionString("tarefasConnection");
        var serverVersion = ServerVersion.AutoDetect(connectionString);
        opt.UseMySql(connectionString, serverVersion);
    });

如果不用依赖注入,就需要在DbContext的实现类里面添加配置信息

public class UserContext:DbContext
{
    public UserContext(DbContextOptions options) : base(options) { }
    public DbSet<User> Users { get; set; } = null!;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseMySql("server=localhost;user=root;password=password;database=database", new MySqlServerVersion(new Version(8, 0, 12)));
    }

}

4、数据模型要添加属性进行映射

[Table("User")]
public class User
{
    [Key]
    [Column("id")]
    public int id { get; set; }
    [Column("name")]
    public string? name { get; set; }
    [Column("gender")]
    public string? gender { get; set; }
    [Column("phone")]
    public string? phone { get; set; }
}

2、dbup-mysql管理SQL脚本

https://dbup.readthedocs.io/en/latest/

可以将每个要升级数据库的脚本放在一个单独的文件里面,dbup根据脚本名顺序执行,并且记住已执行脚本,再次运行DbUp,也只会执行新的脚本。

1、安装库dbup-mysql

2、在配置文件中的配置

var connectionString = "Server=localhost;Database=hdtest;Uid=root;Pwd=111111;";
    EnsureDatabase.For.MySqlDatabase(connectionString); //检查目标数据库是否存在,如果不存在,它将创建数据库,然后运行脚本
    var scriptsPath = "./Scripts";
    var upgrader = DeployChanges.To.MySqlDatabase(connectionString)
        .WithScriptsFromFileSystem(scriptsPath)
        .LogToConsole()
        .Build();
    var result = upgrader.PerformUpgrade();
    if (!result.Successful)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(result.Error);
        Console.ResetColor();
        Environment.Exit(0);
    }
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("Success!");
    Console.ResetColor();

内存数据库

直接在Program.cs中添加:

builder.Services.AddDbContext<UserContext>(opt =>
          opt.UseInMemoryDatabase("UserList"));

Sqlite数据库

https://learn.microsoft.com/zh-cn/training/modules/build-web-api-minimal-database/5-exercise-use-sqlite-database

1、安装库
Microsoft.EntityFrameworkCore.Sqlite

2、Program.cs中注册服务

var connectionString = builder.Configuration.GetConnectionString("Users") ?? "Data Source=Users.db";
builder.Services.AddSqlite<UserContext>(connectionString);

其他迁移什么的命令看上面的链接!!!

最后编辑:2023年07月19日 ©著作权归作者所有