EF Coreの使用方法: .NET Coreでのデータベース操作

1. NuGetパッケージのインストール

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore:EF Coreフレームワークの主要なパッケージ<br></br>Microsoft.EntityFrameworkCore.SqlServer: SQL Serverデータベース用の拡張。同様に、MySQLやSQLiteなども利用可能。<br></br>Microsoft.EntityFrameworkCore.Design:既存のデータベースからモデルコードを生成するためのツール。<br></br>

2. エンティティクラスの追加

public class User
{
    /// <summary>
    /// 自動生成ID
    /// </summary>
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; } = DateTime.Now;
    public DateTime UpdatedAt { get; set; } = DateTime.Now;
    public Guid Uid { get; set; }
    public bool IsDeleted { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public DateTime RegistrationTime { get; set; }
    public DateTime LastLogin { get; set; }
    public bool IsActive { get; set; }
}

3. データベースコンテキストクラスの追加

public class AppDbContext : DbContext
{
    public DbSet<User> Users { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Server=.;Database=MyApp;User Id=sa;Password=Dbuser2015;", opt =>
            {
                opt.CommandTimeout(1000);
            });
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<User>(u =>
        {
            u.ToTable("Users");
            u.HasIndex(u => new
            {
                u.Name,
                u.IsActive
            });
        });
    }
}

4. DbContextのDI設定と接続文字列の追加

public void ConfigureServices(IServiceCollection services)
{
    // データベースコンテキストの登録
    services.AddDbContext<AppDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    }, ServiceLifetime.Scoped);
}
"ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=MyApp;User Id=sa;Password=Dbuser2015;"
  }

5. データベースの初期化と更新

5.1 EF Coreコマンドラインツールのインストール

dotnet tool install --global dotnet-ef

コマンドラインツールの更新が必要な場合は以下のコマンドを実行

dotnet tool update --global dotnet-ef
5.2 データベースの生成、更新、削除
1. 生成
    dotnet ef migrations add Initial --context AppDbContext
2. 更新
    dotnet ef database update
3. 削除
    dotnet ef migrations remove

生成または更新後、EF CoreはMigrationsディレクトリを作成し、変更履歴を記録します。

6. データ構造の公開

Migrationのバージョンファイルに基づいて、データベース構造のアップグレードSQLを自動生成できます。

dotnet ef migrations script 20201026033234_Initial -o init.sql --startup-project ../MyApp --context AppDbContext

また、異なるコードバージョン間の差分SQLも生成可能です。

dotnet ef migrations script 20201026033234_Initial -o init.sql 20201026061627_Initial 20201026062005_UpUserAddDept

これにより、20201026061627_Initial から 20201026062005_UpUserAddDept までのデータベース構造のアップグレードSQLが生成されます。

タグ: .NET Core Entity Framework Core SQL Server C# DbContext

6月1日 11:40 投稿