在 .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 walkthrough, you will create a .NET Core console app that performs basic data access against a SQLite database using Entity Framework Core. 您將使用移轉,以便從您的模型來建立資料庫。You will use migrations to create the database from your 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 上檢視此文章的範例 (英文)。You can view this article's sample on GitHub.

必要條件Prerequisites

若要完成此逐步解說,必須符合下列必要條件:The following prerequisites are needed to complete this walkthrough:

  • 支援 .NET Core 的作業系統。An operating system that supports .NET Core.
  • .NET Core SDK 2.0 (不過,指示也可用來建立使用先前版的應用程式,且幾乎不必修改)。The .NET Core SDK 2.0 (although the instructions can be used to create an application with a previous version with very few modifications).

建立新專案Create a new project

  • 為您的專案建立新的 ConsoleApp.SQLite 資料夾,並使用 dotnet 命令將 .NET Core 應用程式填入該資料夾。Create a new ConsoleApp.SQLite folder for your project and use the dotnet command to populate it with a .NET Core app.
mkdir ConsoleApp.SQLite
cd ConsoleApp.SQLite/
dotnet new console

安裝 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
  • 手動編輯 ConsoleApp.SQLite.csproj,以將 DotNetCliToolReference 加入 Microsoft.EntityFrameworkCore.Tools.DotNet:Manually edit ConsoleApp.SQLite.csproj to add a DotNetCliToolReference to Microsoft.EntityFrameworkCore.Tools.DotNet:

    <ItemGroup>
      <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    </ItemGroup>
    

ConsoleApp.SQLite.csproj 現在應該會包含下列程式碼:ConsoleApp.SQLite.csproj should now contain the following:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" />
  </ItemGroup>
</Project>

注意:上列所使用的版本號碼,為發行時正確的版本號碼。Note: The version numbers used above were correct at the time of publishing.

  • 執行 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 List<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 would put each class in a separate file and put the connection string in a configuration file. 為了簡化教學課程,我們會將所有項目放在一個檔案中。To keep the tutorial simple, we are putting everything in one file.

建立資料庫Create the database

一旦有模型之後,就可以使用移轉來建立資料庫。Once you have a model, you can 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.

注意

在 SQLite 中使用相對路徑時,路徑會相對於應用程式的主要組件。When using relative paths with SQLite, the path will be relative to the application's main assembly. 在此範例中,主要的二進位檔是 bin/Debug/netcoreapp2.0/ConsoleApp.SQLite.dll,因此 SQLite 資料庫將位於 bin/Debug/netcoreapp2.0/blogging.db 中。In this sample, the main binary is bin/Debug/netcoreapp2.0/ConsoleApp.SQLite.dll, so the SQLite database will be in bin/Debug/netcoreapp2.0/blogging.db.

使用您的模型Use your 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:

    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 your model, you can use the dotnet ef migrations add command to scaffold a new migration to make the corresponding schema changes to the database. 檢查完已建立結構的程式碼之後 (並進行任何必要的變更),就可以使用 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 changes to the database.
  • EF 在資料庫中使用 __EFMigrationsHistory 資料表,以確認已經套用至資料庫的移轉。EF uses a __EFMigrationsHistory table in the database to keep track of which migrations have already been applied to the database.
  • 由於 SQLite 中的限制,SQLite 不支援所有移轉 (結構描述變更)。SQLite does not support all migrations (schema changes) due to limitations in SQLite. 請參閱 SQLite 限制See SQLite Limitations. 針對新的開發,當模型變更時,請考慮捨棄資料庫並建立一個新的資料庫,而不是使用移轉。For new development, consider dropping the database and creating a new one rather than using migrations when your model changes.

其他資源Additional Resources