Entity Framework Core でデータベースを作成するコードを紹介します。
概要
Entity Framework Core でデータベースをドロップする場合には、コンテキストオブジェクトのDatabaseプロパティの EnsureCreated() メソッドを呼び出します。
プログラム1: SQL Serverの例
Windows Formアプリケーション(.NET 7)を作成します。
UI
下図のフォームを作成します。
今回のプログラムではボタンを1つのみ[Create Database](button1)を利用します。
コード
以下のコードを記述します。
データベースコンテキストのコードファイルです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace EntityFrameworkCoreCreateDatabaseSqlServer
{
internal class MyDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=(データベースサーバーのホスト名またはIPアドレス);Initial Catalog=iPentecSandBox3;User ID=(接続ID);Password=(パスワード)");
}
}
}
フォームのコードです。button1のクリックイベントを実装しています。
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
namespace EntityFrameworkCoreCreateDatabaseSqlServer
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyDbContext mdc = new MyDbContext();
mdc.Database.EnsureCreated();
textBox1.Text += "データベースを作成しました。\r\n";
}
}
}
解説
データベースコンテキストオブジェクトを作成します。
MyDbContext mdc = new MyDbContext();
データベースコンテキストオブジェクトの、Databaseプロパティの EnsureCreated() メソッドを呼び出し、データベースを作成します。
mdc.Database.EnsureCreated();
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[Create Database]ボタンをクリックします。データベースが作成された旨のメッセージがテキストボックスに表示されます。
データベースサーバーを確認します。接続文字列に設定したデータベースが作成されていることが確認できます。
Entity Framework Core でデータベースの作成ができました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2023-05-08
作成日: 2022-11-25