在通用 Windows 平台 (UWP) 上使用 EF Core 搭配新資料庫的使用者入門Getting Started with EF Core on Universal Windows Platform (UWP) with a New Database

在此教學課程中,您將建置通用 Windows 平台 (UWP) 應用程式,該應用程式將使用 Entity Framework Core 對本機 SQLite 資料庫執行基本資料存取。In this tutorial, you build a Universal Windows Platform (UWP) application that performs basic data access against a local SQLite database using Entity Framework Core.

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

必要條件Prerequisites

重要

本教學課程使用 Entity Framework Core 移轉命令來建立和更新資料庫的結構描述。This tutorial uses Entity Framework Core migrations commands to create and update the schema of the database. 這些命令不能直接搭配 UWP 專案使用。These commands don't work directly with UWP projects. 因此,應用程式的資料模型會放在共用程式庫專案中,再使用不同的 .NET Core 主控台應用程式執行該命令。For this reason, the application's data model is placed in a shared library project, and a separate .NET Core console application is used to run the commands.

建立程式庫專案來保存資料模型Create a library project to hold the data model

  • 開啟 Visual StudioOpen Visual Studio

  • [檔案] > [新增] > [專案]File > New > Project

  • 從左側功能表選取 [已安裝] > [Visual C#] > [.NET Standard]。From the left menu select Installed > Visual C# > .NET Standard.

  • 選取 [類別庫 (.NET Standard)] 範本。Select the Class Library (.NET Standard) template.

  • 將專案命名為 Blogging.ModelName the project Blogging.Model.

  • 將方案命名為 BloggingName the solution Blogging.

  • 按一下 [確定 Deploying Office Solutions]。Click OK.

於資料模型專案中安裝 Entity Framework Core 執行階段Install Entity Framework Core runtime in the data model project

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

  • [工具] -> [NuGet 套件管理員] -> [套件管理員主控台]Tools > NuGet Package Manager > Package Manager Console.

  • 請確定已在套件管理員主控台中選取程式庫專案 Blogging.Model 作為預設專案Make sure that the library project Blogging.Model is selected as the Default Project in the Package Manager Console.

  • 執行 Install-Package Microsoft.EntityFrameworkCore.SqliteRun Install-Package Microsoft.EntityFrameworkCore.Sqlite

建立資料模型Create the data model

現在開始定義組成模型的 DbContext 與實體類別。Now it's time to define the DbContext and entity classes that make up the model.

  • 刪除 Class1.csDelete Class1.cs.

  • 使用下列程式碼建立 Model.csCreate Model.cs with the following code:

    using Microsoft.EntityFrameworkCore;
    using System.Collections.Generic;
    
    namespace Blogging.Model
    {
        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; }
        }
    }
    

建立新的主控台專案以執行移轉命令Create a new console project to run migrations commands

  • 在 [方案總管] 中,以滑鼠右鍵按一下方案,然後選擇 [新增] > [新增專案]。In Solution Explorer, right-click the solution, and then choose Add > New Project.

  • 從左側功能表選取 [已安裝] > [Visual C#] > [.NET Core]。From the left menu select Installed > Visual C# > .NET Core.

  • 選取 [主控台應用程式 (.NET Core)] 專案範本。Select the Console App (.NET Core) project template.

  • 將專案命名為 Blogging.Migrations.Startup,然後按一下 [確定]。Name the project Blogging.Migrations.Startup, and click OK.

  • 新增從 Blogging.Migrations.Startup 專案到 Blogging.Model 專案的專案參考。Add a project reference from the Blogging.Migrations.Startup project to the Blogging.Model project.

在移轉啟動專案中安裝 Entity Framework Core 工具Install Entity Framework Core tools in the migrations startup project

若要在套件管理員主控台中啟用 EF Core 移轉命令,請在主控台應用程式中安裝 EF Core 工具。To enable the EF Core migration commands in the Package Manager Console, install the EF Core tools package in the console application.

  • [工具] > [NuGet 套件管理員] > [套件管理員主控台]Tools > NuGet Package Manager > Package Manager Console

  • 執行 Install-Package Microsoft.EntityFrameworkCore.Tools -ProjectName Blogging.Migrations.StartupRun Install-Package Microsoft.EntityFrameworkCore.Tools -ProjectName Blogging.Migrations.Startup

建立初始移轉Create the initial migration

建立初始遷移,並將主控台應用程式指定為啟動專案。Create the initial migration, specifying the console application as the startup project.

  • 執行 Add-Migration InitialCreate -StartupProject Blogging.Migrations.StartupRun Add-Migration InitialCreate -StartupProject Blogging.Migrations.Startup

此命令會建立移轉的支架,以針對您的資料模型建立一組初始資料庫資料表。This command scaffolds a migration that creates the initial set of database tables for your data model.

建立 UWP 專案Create the UWP project

  • 在 [方案總管] 中,以滑鼠右鍵按一下方案,然後選擇 [新增] > [新增專案]。In Solution Explorer, right-click the solution, and then choose Add > New Project.

  • 從左側功能表中,選取 [已安裝] > [Visual C#] > [Windows 通用]。From the left menu select Installed > Visual C# > Windows Universal.

  • 選取 [空白應用程式 (通用 Windows)] 專案範本。Select the Blank App (Universal Windows) project template.

  • 將專案命名為 Blogging.UWP,然後按一下 [確定]Name the project Blogging.UWP, and click OK

重要

至少將目標與最低版本設定為 Windows 10 Fall Creators Update (10.0; build 16299.0)Set the target and minimum versions to at least Windows 10 Fall Creators Update (10.0; build 16299.0). 舊版 Windows 10 不支援 Entity Framework Core 所需的 .NET Standard 2.0。Previous versions of Windows 10 do not support .NET Standard 2.0, which is required by Entity Framework Core.

新增程式碼以在應用程式啟動時建立資料庫Add code to create the database on application startup

因為您要在執行應用程式的裝置上建立資料庫,請新增程式碼,在應用程式啟動時將任何擱置中的移轉套用至本機資料庫。Since you want the database to be created on the device that the app runs on, add code to apply any pending migrations to the local database on application startup. 第一次執行應用程式時,這會負責建立本機資料庫。The first time that the app runs, this will take care of creating the local database.

  • 新增從 Blogging.UWP 專案到 Blogging.Model 專案的專案參考。Add a project reference from the Blogging.UWP project to the Blogging.Model project.

  • 開啟 App.xaml.csOpen App.xaml.cs.

  • 加入醒目提示的程式碼,以套用任何擱置中的移轉。Add the highlighted code to apply any pending migrations.

    using Blogging.Model;
    using Microsoft.EntityFrameworkCore;
    using System;
    using Windows.ApplicationModel;
    using Windows.ApplicationModel.Activation;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    
    namespace Blogging.UWP
    {
        /// <summary>
        /// Provides application-specific behavior to supplement the default Application class.
        /// </summary>
        sealed partial class App : Application
        {
            /// <summary>
            /// Initializes the singleton application object.  This is the first line of authored code
            /// executed, and as such is the logical equivalent of main() or WinMain().
            /// </summary>
            public App()
            {
                this.InitializeComponent();
                this.Suspending += OnSuspending;
    
                using (var db = new BloggingContext())
                {
                    db.Database.Migrate();
                }
            }
    
            /// <summary>
            /// Invoked when the application is launched normally by the end user.  Other entry points
            /// will be used such as when the application is launched to open a specific file.
            /// </summary>
            /// <param name="e">Details about the launch request and process.</param>
            protected override void OnLaunched(LaunchActivatedEventArgs e)
            {
                Frame rootFrame = Window.Current.Content as Frame;
    
                // Do not repeat app initialization when the Window already has content,
                // just ensure that the window is active
                if (rootFrame == null)
                {
                    // Create a Frame to act as the navigation context and navigate to the first page
                    rootFrame = new Frame();
    
                    rootFrame.NavigationFailed += OnNavigationFailed;
    
                    if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                    {
                        //TODO: Load state from previously suspended application
                    }
    
                    // Place the frame in the current Window
                    Window.Current.Content = rootFrame;
                }
    
                if (e.PrelaunchActivated == false)
                {
                    if (rootFrame.Content == null)
                    {
                        // When the navigation stack isn't restored navigate to the first page,
                        // configuring the new page by passing required information as a navigation
                        // parameter
                        rootFrame.Navigate(typeof(MainPage), e.Arguments);
                    }
                    // Ensure the current window is active
                    Window.Current.Activate();
                }
            }
    
            /// <summary>
            /// Invoked when Navigation to a certain page fails
            /// </summary>
            /// <param name="sender">The Frame which failed navigation</param>
            /// <param name="e">Details about the navigation failure</param>
            void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
            {
                throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
            }
    
            /// <summary>
            /// Invoked when application execution is being suspended.  Application state is saved
            /// without knowing whether the application will be terminated or resumed with the contents
            /// of memory still intact.
            /// </summary>
            /// <param name="sender">The source of the suspend request.</param>
            /// <param name="e">Details about the suspend request.</param>
            private void OnSuspending(object sender, SuspendingEventArgs e)
            {
                var deferral = e.SuspendingOperation.GetDeferral();
                //TODO: Save application state and stop any background activity
                deferral.Complete();
            }
        }
    }
    

提示

若您變更模型,請使用 Add-Migration 命令來建立新移轉的支架,以將相對應的變更套用到資料庫。If you change your model, use the Add-Migration command to scaffold a new migration to apply the corresponding changes to the database. 應用程式啟動時,會將任何擱置中的移轉套用至每個裝置上的本機資料庫。Any pending migrations will be applied to the local database on each device when the application starts.

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.

使用資料模型Use the data model

您現在可使用 EF Core 執行資料存取。You can now use EF Core to perform data access.

  • 開啟 MainPage.xamlOpen MainPage.xaml.

  • 加入下列醒目提示的頁面載入處理常式和 UI 內容Add the page load handler and UI content highlighted below

<Page
    x:Class="Blogging.UWP.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Blogging.UWP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Loaded="Page_Loaded">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel>
            <TextBox Name="NewBlogUrl"></TextBox>
            <Button Click="Add_Click">Add</Button>
            <ListView Name="Blogs">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Url}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackPanel>
    </Grid>
</Page>

現在加入程式碼,以連接 UI 與資料庫Now add code to wire up the UI with the database

  • 開啟 MainPage.xaml.csOpen MainPage.xaml.cs.

  • 從下列清單中加入醒目提示的程式碼:Add the highlighted code from the following listing:

using Blogging.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace Blogging.UWP
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            using (var db = new BloggingContext())
            {
                Blogs.ItemsSource = db.Blogs.ToList();
            }
        }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            using (var db = new BloggingContext())
            {
                var blog = new Blog { Url = NewBlogUrl.Text };
                db.Blogs.Add(blog);
                db.SaveChanges();

                Blogs.ItemsSource = db.Blogs.ToList();
            }
        }
    }
}

您現在可以執行應用程式來查看運作狀況。You can now run the application to see it in action.

  • 在 [方案總管] 中,以滑鼠右鍵按一下 [Blogging.UWP] 專案,然後選取 [部署]。In Solution Explorer, right-click the Blogging.UWP project and then select Deploy.

  • Blogging.UWP 設定為起始專案。Set Blogging.UWP as the startup project.

  • [偵錯] > [啟動但不偵錯]Debug > Start Without Debugging

    應用程式會建置並執行。The app builds and runs.

  • 輸入 URL 並按一下 [加入] 按鈕Enter a URL and click the Add button

    影像

    影像

    大功告成!Tada! 您現在有一個執行 Entity Framework Core 的簡單 UWP 應用程式了。You now have a simple UWP app running Entity Framework Core.

後續步驟Next steps

針對搭配 UWP 使用 EF Core 時應該知道的相容性與效能資訊,請參閱 EF Core 提供的 .NET 實作支援For compatibility and performance information that you should know when using EF Core with UWP, see .NET implementations supported by EF Core.

請參閱此文件中的其他文章,以深入了解 Entity Framework Core 的功能。Check out other articles in this documentation to learn more about Entity Framework Core features.