EFCore 开始

1. 数据准备

新建类库项目——实体

NuGet安装:

  1. Microsoft.EntityFrameworkCore

新建类库项目——DbContext

NuGet安装:

  1. Microsoft.EntityFrameworkCore

    1. Pomelo.EntityFrameworkCore.MySql(对应数据库安装)

新建可执行项目——web、console

NuGet安装:

  1. Microsoft.EntityFrameworkCore.Tools

2. 数据库迁移

在数据库上下文项目(DbContext所在项目)中执行

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

  2. 执行数据库迁移

    1. 生产环境:Script-Migration
    2. 开发环境:Update-Database

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();
        }
    }
}
上一篇:JavaScript基础——内置对象(数组对象)


下一篇:jQuery width( ) 方法