開始使用 EF Core

在此教學課程中,您會建置 .NET Core 主控台應用程式,它會使用 Entity Framework Core 對 SQLite 資料庫執行資料存取。

您可以在 Windows 上使用 Visual Studio,或在 Windows、macOS 或 Linux 上使用 .NET CLI 來遵循本教學課程。

在 GitHub 上檢視此文章的範例

必要條件

安裝下列軟體:

建立新專案

dotnet new console -o EFGetStarted
cd EFGetStarted

安裝 Entity Framework Core

若要安裝 EF Core,請為希望作為目標的 EF Core 資料庫提供者,安裝此套件。 本教學課程使用 SQLite,因為它會在 .NET 支援的所有平台上執行。 如需可用的提供者清單,請參閱資料庫提供者

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 命令會建立移轉的 Scaffolding,以針對模型建立一組初始資料表。 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

下一步