共用方式為


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命令會生成遷移程序,以建立模型的初始資料表集。 命令 database update 會建立資料庫,並將新的移轉套用至資料庫。

建立、讀取、更新、刪除 &

  • 開啟 Program.cs ,並以下列程式代碼取代內容:

    using System;
    using System.Linq;
    using Microsoft.EntityFrameworkCore;
    
    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" });
    await db.SaveChangesAsync();
    
    // Read
    Console.WriteLine("Querying for a blog");
    var blog = await db.Blogs
        .OrderBy(b => b.BlogId)
        .FirstAsync();
    
    // 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!" });
    await db.SaveChangesAsync();
    
    // Delete
    Console.WriteLine("Delete the blog");
    db.Remove(blog);
    await db.SaveChangesAsync();
    

執行應用程式

dotnet run

後續步驟