在 .NET Core 主控台應用程式上使用 EF Core 搭配新資料庫的使用者入門Getting Started with EF Core on .NET Core Console App with a New database

在此教學課程中,您會建置 .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. 您會使用移轉從模型建立資料庫。You use migrations to create the database from the model. 如需使用 ASP.NET Core MVC 的 Visual Studio 版本,請參閱 ASP.NET Core - 新資料庫See ASP.NET Core - New database for a Visual Studio version using ASP.NET Core MVC.

在 GitHub 上檢視此文章的範例View this article's sample on GitHub.

必要條件Prerequisites

建立新專案Create a new project

  • 建立新的主控台專案:Create a new console project:

    dotnet new console -o ConsoleApp.SQLite
    

變更目前的目錄Change the current directory

在後續步驟中,我們需要對應用程式發出 dotnet 命令。In subsequent steps, we need to issue dotnet commands against the application.

  • 我們會將目前的目錄變更為應用程式目錄,如下所示:We change the current directory to the application's directory like this:

    cd ConsoleApp.SQLite/
    

安裝 Entity Framework CoreInstall Entity Framework Core

若要使用 EF Core,請針對您要作為目標的資料庫提供者來安裝套件。To use EF Core, install the package for the database provider(s) you want to target. 本逐步解說使用 SQLite。This walkthrough uses SQLite. 如需可用的提供者清單,請參閱資料庫提供者For a list of available providers see Database Providers.

  • 安裝 Microsoft.EntityFrameworkCore.Sqlite 和 Microsoft.EntityFrameworkCore.DesignInstall Microsoft.EntityFrameworkCore.Sqlite and Microsoft.EntityFrameworkCore.Design

    dotnet add package Microsoft.EntityFrameworkCore.Sqlite
    dotnet add package Microsoft.EntityFrameworkCore.Design
    
  • 執行 dotnet restore 以安裝新的套件。Run dotnet restore to install the new packages.

建立模型Create the model

定義組成模型的內容和實體類別。Define a context and entity classes that make up your model.

  • 建立具有下列內容的新 Model.cs 檔案。Create a new Model.cs file with the following contents.

    using Microsoft.EntityFrameworkCore;
    using System.Collections.Generic;
    
    namespace ConsoleApp.SQLite
    {
        public class BloggingContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
            public DbSet<Post> Posts { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlite("Data Source=blogging.db");
            }
        }
    
        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { get; set; }
    
            public ICollection<Post> Posts { get; set; }
        }
    
        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; }
        }
    }
    

祕訣:在實際的應用程式中,您會將每個類別放在不同的檔案中,然後將連接字串放在設定檔或環境變數中。Tip: In a real application, you put each class in a separate file and put the connection string in a configuration file or environment variable. 為了簡化教學課程,所有項目會統一放在一個檔案中。To keep the tutorial simple, everything is contained in one file.

建立資料庫Create the database

一旦有模型後,您就可以使用移轉來建立資料庫。Once you have a model, you use migrations to create a database.

  • 執行 dotnet ef migrations add InitialCreate 以建立移轉的結構,並針對模型建立一組初始的資料表。Run dotnet ef migrations add InitialCreate to scaffold a migration and create the initial set of tables for the model.
  • 執行 dotnet ef database update 以將新的移轉套用至資料庫。Run dotnet ef database update to apply the new migration to the database. 此命令會建立資料庫,然後才套用移轉。This command creates the database before applying migrations.

blogging.db* SQLite DB 位於專案目錄中。The blogging.db* SQLite DB is in the project directory.

使用模型Use the model

  • 開啟 Program.cs 並使用下列程式碼來取代內容:Open Program.cs and replace the contents with the following code:

    using System;
    
    namespace ConsoleApp.SQLite
    {
        public class Program
        {
            public static void Main()
            {
                using (var db = new BloggingContext())
                {
                    db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                    var count = db.SaveChanges();
                    Console.WriteLine("{0} records saved to database", count);
    
                    Console.WriteLine();
                    Console.WriteLine("All blogs in database:");
                    foreach (var blog in db.Blogs)
                    {
                        Console.WriteLine(" - {0}", blog.Url);
                    }
                }
            }
        }
    }
    
  • 從主控台測試應用程式。Test the app from the console. 請參閱 Visual Studio 注意事項 以透過 Visual Studio 執行應用程式。See the Visual Studio note to run the app from Visual Studio.

    dotnet run

    有一個部落格儲存至資料庫,且所有部落格的詳細資料會在主控台中顯示。One blog is saved to the database and the details of all blogs are displayed in the console.

    ConsoleApp.SQLite>dotnet run
    1 records saved to database
    
    All blogs in database:
    - http://blogs.msdn.com/adonet
    

變更模型:Changing the model:

  • 若要變更模型,您可以使用 dotnet ef migrations add 命令來建立新的移轉支架。If you make changes to the model, you can use the dotnet ef migrations add command to scaffold a new migration. 一旦檢查支架程式碼 (並進行任何必要的變更),您就可以使用 dotnet ef database update 命令將結構描述變更套用到資料庫。Once you have checked the scaffolded code (and made any required changes), you can use the dotnet ef database update command to apply the schema changes to the database.
  • EF Core 在資料庫中使用 __EFMigrationsHistory 資料表,以追蹤已套用到資料庫的移轉。EF Core uses a __EFMigrationsHistory table in the database to keep track of which migrations have already been applied to the database.
  • SQLite 資料庫引擎不支援大部分其他關聯式資料庫所支援的特定結構描述變更。The SQLite database engine doesn't support certain schema changes that are supported by most other relational databases. 例如,不支援 DropColumn 作業。For example, the DropColumn operation is not supported. EF Core 移轉將會產生這些作業的程式碼。EF Core Migrations will generate code for these operations. 但若您嘗試將它們套用到資料庫或產生指令碼,EF Core 會擲回例外狀況。But if you try to apply them to a database or generate a script, EF Core throws exceptions. 請參閱 SQLite 限制See SQLite Limitations. 針對新的開發,當模型變更時,請考慮捨棄資料庫並建立一個新的資料庫,而不是使用移轉。For new development, consider dropping the database and creating a new one rather than using migrations when the model changes.

透過 Visual Studio 來執行Run from Visual Studio

若要透過 Visual Studio 執行此範例,您必須將工作目錄手動設定為專案的根目錄。To run this sample from Visual Studio, you must set the working directory manually to be the root of the project. 如果您未設定工作目錄,就會擲回下列 Microsoft.Data.Sqlite.SqliteExceptionSQLite Error 1: 'no such table: Blogs'If you don't set the working directory, the following Microsoft.Data.Sqlite.SqliteException is thrown: SQLite Error 1: 'no such table: Blogs'.

若要設定工作目錄:To set the working directory:

  • 在 [方案總管] 中,以滑鼠右鍵按一下專案,然後選取 [屬性]。In Solution Explorer, right click the project and then select Properties.
  • 選取左窗格中的 [偵錯] 索引標籤。Select the Debug tab in the left pane.
  • 工作目錄設定為專案目錄。Set Working directory to the project directory.
  • 儲存變更。Save the changes.

其他資源Additional Resources