開始使用 EF CoreGetting Started with EF Core

在此教學課程中,您會建置 .NET Core 主控台應用程式,它會使用 Entity Framework Core 對 SQLite 資料庫執行資料存取。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 CoreInstall 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. 本教學課程會使用 SQLite,因為它可以在 .NET Core 支援的所有平台上執行。This tutorial uses SQLite because it runs on all platforms that .NET Core supports. 如需可用的提供者清單,請參閱資料庫提供者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.csIn 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 命令會建立移轉的 Scaffolding,以針對模型建立一組初始資料表。The migrations command scaffolds a migration to create the initial set of tables for the model. database update 命令會建立資料庫,並對資料庫套用新的移轉。The database 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

dotnet run

後續步驟Next steps