0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#(dotnet core)でのmysql db contextの作成(メモ)

Last updated at Posted at 2022-09-17

自分で使うためのメモ

ASP.NET Core/コンソールなどでも使える

必要なパッケージ(NuGetする)

  • Pomelo.EntityFrameworkCore.MySql
  • MySql.Data

DbContext継承クラスを作成

using Microsoft.EntityFrameworkCore;
using MySqlConnector;

public class NekochayaDbContext : DbContext
{
    /// <summary>
    /// connection string を生成するため
    /// </summary>
    private MySqlConnectionStringBuilder Config { set; get; }


    /// <summary>
    /// 設定
    /// </summary>
    /// <param name="config"></param>
    public NekochayaDbContext(IConfiguration config)
    {
        Config = new MySqlConnectionStringBuilder();
        Config.Server = config.GetSection("NekochayaDB").GetValue<string>("Host");
        Config.Port = 3306;
        Config.UserID = config.GetSection("NekochayaDB").GetValue<string>("User");
        Config.Password = config.GetSection("NekochayaDB").GetValue<string>("Pass");
        Config.Database = config.GetSection("NekochayadB").GetValue<string>("Schema");
        Config.CharacterSet = "utf8mb4";
    }


    /// <summary>
    /// コネクション情報の反映
    /// </summary>
    /// <param name="optionsBuilder"></param>
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
        optionsBuilder.UseMySql(Config.ConnectionString, ServerVersion.AutoDetect(Config.ConnectionString));

    /// <summary>
    /// 主キーなどの設定はここ
    /// </summary>
    /// <param name="modelBuilder"></param>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

    }
}


0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?