NuGet安装:
NuGet安装:
NuGet安装:
Add-Migration [Name] 生成数据库操作文件
执行数据库迁移
"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();
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章