EF Core の概要Getting Started with EF Core
このチュートリアルでは、Entity Framework Core を使用して SQLite データベースに対してデータ アクセスを実行する .NET Core コンソール アプリを作成します。In this tutorial, you create a .NET Core console app that performs data access against a SQLite database using Entity Framework Core.
このチュートリアルは、Windows 上の Visual Studio または Windows、macOS または Linux. 上の .NET Core CLI を対象としています。You can follow the tutorial by using Visual Studio on Windows, or by using the .NET Core CLI on Windows, macOS, or Linux.
この記事のサンプルは GitHub で確認してください。View this article's sample on GitHub.
前提条件Prerequisites
次のソフトウェアをインストールします。Install the following software:
新しいプロジェクトを作成するCreate a new project
dotnet new console -o EFGetStarted
cd EFGetStarted
Entity Framework Core をインストールするInstall Entity Framework Core
EF Core をインストールするには、対象となる EF Core データベース プロバイダーのパッケージをインストールします。To install EF Core, you install the package for the EF Core database provider(s) you want to target. このチュートリアルでは、.NET Core がサポートしているすべてのプラットフォームで実行できるため、SQLite を使用しています。This tutorial uses SQLite because it runs on all platforms that .NET Core supports. 使用可能なプロバイダーの一覧については、「Database Providers」 (データベース プロバイダー) をご覧ください。For a list of available providers, see Database Providers.
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
モデルを作成するCreate the model
モデルを構成するコンテキスト クラスおよびエンティティ クラスを定義します。Define a context class and entity classes that make up the model.
- 以下のコードを使用して、プロジェクト ディレクトリで Model.cs を作成しますIn the project directory, create Model.cs with the following code
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace EFGetStarted
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=blogging.db");
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; } = new List<Post>();
}
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 では、既存のデータベースからモデルをリバース エンジニアリングすることもできます。EF Core can also reverse engineer a model from an existing database.
ヒント :このアプリケーションでは、わかりやすくするために意図的に事をシンプルにしています。Tip: This application intentionally keeps things simple for clarity. 運用アプリケーションのコードに、接続文字列 は格納しないでください。Connection strings should not be stored in the code for production applications. また、各 C# クラスを独自のファイルに分割することが必要な場合もあります。You may also want to split each C# class into its own file.
データベースの作成Create the database
次の手順では、移行を使用し、データベースを作成しています。The following steps use migrations to create a database.
次のコマンドを実行します。Run the following commands:
dotnet tool install --global dotnet-ef dotnet add package Microsoft.EntityFrameworkCore.Design dotnet ef migrations add InitialCreate dotnet ef database update
これにより、プロジェクトでコマンドを実行するために必要な dotnet ef と設計パッケージがインストールされます。This installs dotnet ef and the design package which is required to run the command on a project. この
migrations
では、モデルの最初のテーブル セットを作成する移行がスキャフォールディングされます。Themigrations
command scaffolds a migration to create the initial set of tables for the model.database update
コマンドではデータベースが作成され、それに新しい移行が適用されます。Thedatabase update
command creates the database and applies the new migration to it.
作成、読み取り、更新、および削除Create, read, update & delete
Program.cs を開き、内容を次のコードに置き換えます。Open Program.cs and replace the contents with the following code:
using System; using System.Linq; namespace EFGetStarted { internal class Program { private static void Main() { using (var db = new BloggingContext()) { // Note: This sample requires the database to be created before running. // 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(); } } } }
アプリを実行するRun the app
次のステップNext steps
- Web アプリでの EF Core の使用には、ASP.NET Core のチュートリアルのページを参照してくださいFollow the ASP.NET Core Tutorial to use EF Core in a web app
- LINQ クエリ式について参照してくださいLearn more about LINQ query expressions
- required や maximum length などを指定し、モデルを構成しますConfigure your model to specify things like required and maximum length
- モデルの変更後のデータベース スキーマの更新に、Migrations を使用しますUse Migrations to update the database schema after changing your model