.Net Core 3.0 Windows Form + Entity Framework Core + SQLiteを試したい


環境

  • Windows10 Pro (1903) 64bit
  • Visual Studio 2019
  • .NET Core 3.0

要約すると

.NET Core 3.0でWindows Formがサポートされました。
ASP.NET CoreでEF + SQLiteができるので、WinForm + EF + SQLiteもいけるんじゃね?という発想です。
結論として、CoreじゃないEFと大体同じ手順で出来ましたのでまとめています。
画像が多めで割と長くなりました。

アプローチ

.NET Core Windows Form Appプロジェクトを立てる


Windows Forms App (.NET Core)というなかなかの絵面

ModelとかDbContextとかを別DLLにまとめる




こんな感じのプロジェクト構成です。
WinFormCoreAppTestからEFCoreTestを参照設定しています。

Entity Framework Coreのインストール

Nugetからインストールします。
Microsoft.EntityFramework.Core.SQLite

Microsoft.EntityFramework.Core.Tools

DLL側プロジェクトにクラスを色々追加する

モデル

Product.cs
namespace EFCoreTest
{
    public class Product
    {
        [Key]
        public string ProductId { get; set; }

        public int UnitPrice { get; set; }

        public string Name { get; set; }

        public Product()
        {
            ProductId = Guid.NewGuid().ToString();
            UnitPrice = 0;
            Name = string.Empty;
        }
    }
}

コンテキスト

SampleDbContext.cs
namespace EFCoreTest
{
    public class SampleDbContext : DbContext
    {
        /// <summary>
        /// サンプル用DbSet
        /// </summary>
        public DbSet<Product> Products { get; set; }


        public SampleDbContext() : base()
        {
        }

        public SampleDbContext(DbContextOptions options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=sample.db");      //ここでDBファイルを指定
        }
    }
}

ここまでやったら一度ビルドしておきます。

Migrationクラスを作成してDBファイルを作ります

コマンドを実行します。

add-migrations (Migration)

こんな感じのログが出ます。

出来ました。

InitialCreate.cs
namespace EFCoreTest.Migrations
{
    public partial class InitialCreate : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Products",
                columns: table => new
                {
                    ProductId = table.Column<string>(nullable: false),
                    UnitPrice = table.Column<int>(nullable: false),
                    Name = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Products", x => x.ProductId);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Products");
        }
    }
}

後はMigrationを実際に反映させるので以下のコマンドを実行します。

update-database

あれ?WinFormCoreAppTestのほうに出来た?
まぁ出来てればなんでもいいので次に進みます。

Windows FormのUIを 適当に 作る

簡単にコントロールを配置して画面を作ります。
.NET Core Windows FormでのUI作成は今回の記事の趣旨ではないのでさらっと流します。


デフォルトのアイコンが若干お洒落になってる…!

CRUDを試す

とりあえずサンプルデータを作っておきます。
これが表示されるのでSelectはOK。

とりあえずInsert


一番下が追加されました。

次はUpdate


Sample2ってやつが更新されました。

最後Delete。


Sample3ってやつを削除しました。

CRUD全部OK。素晴らしい。

まとめ

  • .NET Framework Windows Form + Entity Framework (SQLServer)とほぼ同じ手順でSQLite操作ができました。
  • SQLiteのデータベースファイルがどこに出来るか、とか、ビルド時にコピーとか忘れがちかなと思います。
  • Windows Form アプリになるのでデータベースファイルがユーザーの環境に置かれるということで、後からテーブル定義変える場合は別途頭使いそう。

以上です。