EF Core の概要

このチュートリアルでは、Entity Framework Core を使用して SQLite データベースに対してデータ アクセスを実行する .NET Core コンソール アプリを作成します。

このチュートリアルを実行するには、Windows 上の Visual Studio を使うか、Windows、macOS、または Linux 上の .NET CLI を使うことができます。

この記事のサンプルは GitHub で確認してください

前提条件

次のソフトウェアをインストールします。

新しいプロジェクトの作成

dotnet new console -o EFGetStarted
cd EFGetStarted

Entity Framework Core をインストールする

EF Core をインストールするには、対象となる EF Core データベース プロバイダーのパッケージをインストールします。 このチュートリアルでは、.NET がサポートしているすべてのプラットフォームで実行できるため、SQLite を使っています。 使用可能なプロバイダーの一覧については、「Database Providers」 (データベース プロバイダー) をご覧ください。

dotnet add package Microsoft.EntityFrameworkCore.Sqlite

モデルを作成する

モデルを構成するコンテキスト クラスおよびエンティティ クラスを定義します。

  • 以下のコードを使用して、プロジェクト ディレクトリで Model.cs を作成します
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public string DbPath { get; }

    public BloggingContext()
    {
        var folder = Environment.SpecialFolder.LocalApplicationData;
        var path = Environment.GetFolderPath(folder);
        DbPath = System.IO.Path.Join(path, "blogging.db");
    }

    // The following configures EF to create a Sqlite database file in the
    // special "local" folder for your platform.
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; } = new();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

EF Core では、既存のデータベースからモデルをリバース エンジニアリングすることもできます。

ヒント: このアプリケーションでは、わかりやすくするために意図的に物事をシンプルに保っています。 運用アプリケーションのコードに、接続文字列 は格納しないでください。 また、各 C# クラスを独自のファイルに分割することが必要な場合もあります。

データベースの作成

次の手順では、移行を使用し、データベースを作成しています。

  • 次のコマンドを実行します。

    dotnet tool install --global dotnet-ef
    dotnet add package Microsoft.EntityFrameworkCore.Design
    dotnet ef migrations add InitialCreate
    dotnet ef database update
    

    これにより、プロジェクトでコマンドを実行するために必要な dotnet ef と設計パッケージがインストールされます。 この migrations では、モデルの最初のテーブル セットを作成する移行がスキャフォールディングされます。 database update コマンドではデータベースが作成され、それに新しい移行が適用されます。

作成、読み取り、更新、および削除

  • Program.cs を開き、その内容を次のコードに置き換えます。

    using System;
    using System.Linq;
    
    using var db = new BloggingContext();
    
    // Note: This sample requires the database to be created before running.
    Console.WriteLine($"Database path: {db.DbPath}.");
    
    // Create
    Console.WriteLine("Inserting a new blog");
    db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
    db.SaveChanges();
    
    // Read
    Console.WriteLine("Querying for a blog");
    var blog = db.Blogs
        .OrderBy(b => b.BlogId)
        .First();
    
    // Update
    Console.WriteLine("Updating the blog and adding a post");
    blog.Url = "https://devblogs.microsoft.com/dotnet";
    blog.Posts.Add(
        new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
    db.SaveChanges();
    
    // Delete
    Console.WriteLine("Delete the blog");
    db.Remove(blog);
    db.SaveChanges();
    

アプリを実行する

dotnet run

次のステップ