EFCore 开始
阅读原文时间:2023年07月10日阅读:2

1. 数据准备

NuGet安装:

  1. Microsoft.EntityFrameworkCore

NuGet安装:

  1. Microsoft.EntityFrameworkCore

NuGet安装:

  1. Microsoft.EntityFrameworkCore.Tools

2. 数据库迁移

  1. Add-Migration [Name] 生成数据库操作文件

  2. 执行数据库迁移

3. 其他笔记

IOC注入MySQL配置:

"MySqlConnOptions": {
  "Version": {
    "Major": 5,
    "Minor": 7,
    "Build": 23
  },
  "Server": "wosperry.com.cn",
  "Port": 8799,
  "UserId": "wosperry",
  "Password": "Aa123456.",
  "Database": "sd_log"
}


/// <summary>
/// MySQL 配置
/// </summary>
public class MySqlConnOptions
{
    public Version Version { get; set; }
    public string Server { get; set; }
    public int Port { get; set; }
    public string Database { get; set; }
    public string UserId { get; set; }
    public string Password { get; set; }
}


/// <summary>
/// DI
/// </summary>
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MySqlConnOptions>(Configuration.GetSection("MySqlConnOptions"));
    services.AddTransient<SdlContext>();
}


/// <summary>
/// 数据库访问上下文
/// </summary>
public class SdlContext : DbContext
{
    #region 字段
    private readonly IOptionsMonitor<MySqlConnOptions> _optionsMonitor;
    #endregion

    #region 数据
    public DbSet<Staff> Staff;
    #endregion
    /// <summary>
    /// 拼接链接字符串
    /// </summary>
    private string ConnString => $"server={_optionsMonitor.CurrentValue.Server};" +
                $"port={_optionsMonitor.CurrentValue.Port};" +
                $"database={_optionsMonitor.CurrentValue.Database};" +
                $"user id={_optionsMonitor.CurrentValue.UserId};" +
                $"password={_optionsMonitor.CurrentValue.Password}";
    public SdlContext(IOptionsMonitor<MySqlConnOptions> optionsMonitor)
    {
        _optionsMonitor = optionsMonitor;
    }

    /// <summary>
    /// 配置
    /// </summary>
    /// <param name="optionsBuilder"></param>
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseMySql(ConnString, new MySqlServerVersion(_optionsMonitor.CurrentValue.Version), mysqlOptions =>
            {
                mysqlOptions.CharSetBehavior(CharSetBehavior.NeverAppend);
            })
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors();
        }
    }
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章