使用 EF Core 和 Xamarin 消費者入門Getting Started with EF Core and Xamarin

在本教學課程中,您會建立一個 Xamarin. Forms 應用程式,該應用程式會使用 Entity Framework Core 對 SQLite 資料庫執行資料存取。In this tutorial, you create a Xamarin.Forms application that performs data access against a SQLite database using Entity Framework Core.

您可以使用 Windows 上的 Visual Studio 或 Visual Studio for Mac 來遵循教學課程。You can follow the tutorial by using Visual Studio on Windows or Visual Studio for Mac.

提示

您可以檢視本文中的 GitHut 範例You can view this article's sample on GitHub.

必要條件Prerequisites

安裝下列其中一項:Install one of the below:

本檔會針對每個平臺 提供詳細的逐步安裝指示This documentation provides detailed step-by-step installation instructions for each platform.

下載並執行範例專案Download and run the sample project

若要執行及探索此範例應用程式,請下載 GitHub 上的程式碼。To run and explore this sample application, download the code on GitHub.

下載之後,請在 Visual Studio 中開啟方案檔, EFGettingStarted.sln 或 Visual Studio for Mac,然後在您選擇的平臺上執行應用程式。Once downloaded, open the solution file EFGettingStarted.sln in Visual Studio or Visual Studio for Mac and run the application on the platform of your choice.

當應用程式第一次啟動時,它會在本機 SQLite 資料庫中填入兩個代表 blog 的專案。When the app first starts, it will populate the local SQLite database with two entries representing blogs.

所有 blog 清單頁面的螢幕擷取畫面

按一下工具列中的 [ 加入 ] 按鈕。Click the Add button in the toolbar.

將會出現新的頁面,讓您輸入新的 blog 的相關資訊。A new page will appear that allows you to enter information about a new blog.

新 blog [編輯] 頁面的螢幕擷取畫面

填寫所有資訊,然後按一下工具列中的 [ 儲存 ]。Fill out all the info and click Save from the toolbar. 新的 blog 會儲存至應用程式的 SQLite 資料庫,並顯示在清單中。The new blog will save to the app's SQLite database and will show in the list.

您可以按一下清單中的其中一個 blog 專案,查看該 blog 的任何文章。You can click on one of the blog entries in the list and see any posts for that blog.

[Blog] 文章清單頁面的螢幕擷取畫面

在工具列中按一下 [ 加入 ]。Click Add in the toolbar.

接著會出現一個頁面,讓您填寫新的 blog 貼文的相關資訊。A page then appears that allows you to fill out information about a new blog post.

[新增貼文] 頁面的螢幕擷取畫面

填寫所有資訊,然後按一下工具列中的 [ 儲存 ]。Fill out all the information and click Save in the toolbar.

新的貼文將會與您在上一個步驟中按一下的 blog 文章相關聯,並會儲存至應用程式的 SQLite 資料庫,並顯示在清單中。The new post will be associated to the blog post you clicked on in a previous step and will save to the app's SQLite database and show in the list.

返回至 [blog 清單] 頁面。Go back to the blog list page. 並按一下工具列中的 [ 全部刪除 ]。And click Delete All in the toolbar. 然後,將會從應用程式的 SQLite 資料庫中刪除所有的 blog 和其對應的貼文。All blogs and their corresponding posts will then be deleted from the app's SQLite database.

已刪除所有 blog 的應用程式螢幕擷取畫面

探索程式碼Explore the code

下列各節將逐步引導您完成範例專案中的程式碼,該程式碼會使用 EF Core 搭配 Xamarin,從 SQLite 資料庫讀取、建立、更新及刪除資料。The following sections will walk you through the code in the sample project that reads, creates, updates, and deletes data from a SQLite database using EF Core with Xamarin.Forms.

假設您已經熟悉 顯示資料 並在 頁面之間流覽的 Xamarin. Forms 主題。It is assumed that you are familiar with the Xamarin.Forms topics of displaying data and navigating between pages.

重要

Entity Framework Core 使用反映來叫用 Xamarin 連結器可能在 發行 模式設定中去除的函式。Entity Framework Core uses reflection to invoke functions which the Xamarin.iOS linker may strip out while in Release mode configurations. 您可以透過兩種方式來避免這種情況。You can avoid that in one of two ways.

  • 第一個方法是將新增 --linkskip System.CoreiOS 組建選項中的其他 mtouch 引數The first is to add --linkskip System.Core to the Additional mtouch arguments in the iOS Build options.
  • 或者, Linker behavior Don't Linkios 組建選項中將 [Xamarin] 連結器行為設定為。Alternatively set the Xamarin.iOS Linker behavior to Don't Link in the iOS Build options. 本文將詳細說明 xamarin 連結器,包括如何在 xamarin 上設定行為。This article explains more about the Xamarin.iOS linker including how to set the behavior on Xamarin.iOS.

Entity Framework Core NuGet 套件Entity Framework Core NuGet packages

若要使用 EF Core 建立 Xamarin 的 Forms 應用程式,請為 EF Core 資料庫提供 (者安裝套件,) 您想要以 Xamarin 方案中的所有專案為目標。To create Xamarin.Forms apps with EF Core, you install the package for the EF Core database provider(s) you want to target into all of the projects in the Xamarin.Forms solution. 本教學課程使用 SQLite 提供者。This tutorial uses the SQLite provider.

在 Xamarin 方案中的每個專案都需要下列 NuGet 套件。The following NuGet package is needed in each of the projects in the Xamarin.Forms solution.

  • Microsoft.EntityFrameworkCore.Sqlite

模型類別Model classes

在 SQLite 資料庫中透過 EF Core 存取的每個資料表都會在類別中模型化。Each table in the SQLite database accessed through EF Core is modeled in a class. 在此範例中,會使用兩個類別: Blog 以及 Post 可在資料夾中找到的類別 ModelsIn this sample, two classes are used: Blog and Post which can be found in the Models folder.

模型類別只是由屬性所組成,而這些屬性是資料庫中的模型資料行。The model classes are composed only of properties, which model columns in the database.

  • Blog.csBlog.cs

    using System;
    using System.Collections.Generic;
    
    namespace EFGetStarted
    {
        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { get; set; }
    
            public List<Post> Posts { get; set; } = new List<Post>();
        }
    }
    
  • Posts屬性定義和之間的父子式關聯性 Blog PostThe Posts property defines a parent-child relationship between Blog and Post.

  • Post.csPost.cs

    using System;
    namespace EFGetStarted
    {
        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; }
        }
    }
    
  • BlogIdBlog 屬性會與實例的父物件建立關聯 Blog PostThe BlogId and Blog properties relate back to the parent Blog object for the instance of the Post.

資料內容Data context

BloggingContext類別位於 Services 資料夾中,並繼承自 EF Core DbContext 類別。The BloggingContext class is located in the Services folder and inherits from the EF Core DbContext class. DbContext用來將資料庫查詢與變更群組在一起。A DbContext is used to group together database queries and changes.

using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Xamarin.Essentials;

namespace EFGetStarted
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        public BloggingContext()
        {
            SQLitePCL.Batteries_V2.Init();

            this.Database.EnsureCreated();
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string dbPath = Path.Combine(FileSystem.AppDataDirectory, "blogs.db3");

            optionsBuilder
                .UseSqlite($"Filename={dbPath}");
        }
    }
}
  • 此類型類別中的這兩個屬性 DbSet 都是用來在代表 blog 和貼文的基礎資料表上運作。Both properties in this class of type DbSet are used to operate on the underlying tables representing Blogs and Posts.
  • SQLitePCL.Batteries_V2.Init() iOS 上起始 SQLite 的函式需要此項。The SQLitePCL.Batteries_V2.Init() is needed in the constructor to initiate SQLite on iOS.
  • OnConfiguring 函數會在實體裝置上設定 SQLite 資料庫的位置。The OnConfiguring function sets up the location of the SQLite database on the physical device.

建立、讀取、更新及刪除Create, read, update & delete

以下是應用程式中 EF Core 用來存取 SQLite 的一些實例。The following are some instances in the app where EF Core is used to access SQLite.

讀取Read

  • 傳回所有記錄。Return all records.
    • 的函式會傳回 OnAppearing BlogsPage.xaml.cs 所有 Blog 記錄,並將其儲存在 List 變數中。The OnAppearing function of BlogsPage.xaml.cs returns all Blog records and stores them into a List variable.
using (var blogContext = new BloggingContext())
{
    var theBlogs = blogContext.Blogs.ToList();
}
  • 傳回特定記錄。Return specific records.
    • 的函式 OnAppearing PostsPage.xaml.cs 會傳回 Post 包含特定的記錄 BlogIdThe OnAppearing function of PostsPage.xaml.cs returns Post records that contain a specific BlogId.
using (var blogContext = new BloggingContext())
{
    var postList = blogContext.Posts
        .Where(p => p.BlogId == BlogId)
        .ToList();
}

建立Create

  • 插入新的記錄。Insert a new record.
    • Save_Clicked AddBlogPage.xaml.csBlog 物件插入 SQLite 資料庫的功能。The Save_Clicked function of AddBlogPage.xaml.cs inserts a new Blog object into the SQLite database.
var blog = new Blog { Url = blogUrl.Text };

using (var blogContext = new BloggingContext())
{
    blogContext.Add(blog);

    await blogContext.SaveChangesAsync();
}

更新Update

  • 更新現有的記錄。Update an existing record.
    • Save_Clicked的函式會以新的來 AddPostPage.xaml.cs 更新現有的 Blog 物件 PostThe Save_Clicked function of AddPostPage.xaml.cs updates an existing Blog object with a new Post.
var newPost = new Post
{
    BlogId = BlogId,
    Content = postCell.Text,
    Title = titleCell.Text
};

using (var blogContext = new BloggingContext())
{
    var blog = await blogContext
        .Blogs
        .FirstAsync(b => b.BlogId == BlogId);

    blog.Posts.Add(newPost);

    await blogContext.SaveChangesAsync();
}

刪除Delete

  • 刪除具有 cascade 至子記錄的所有記錄。Delete all records with cascade to child records.
    • 的函式會 DeleteAll_Clicked BlogsPage.xaml.cs 刪除 Blog SQLite 資料庫中的所有記錄,並將刪除程式集中至所有 BlogPost 記錄。The DeleteAll_Clicked function of BlogsPage.xaml.cs deletes all the Blog records in the SQLite database and cascades the deletes to all of the Blog child Post records.
using (var blogContext = new BloggingContext())
{
    blogContext.RemoveRange(blogContext.Blogs);

    await blogContext.SaveChangesAsync();
}

後續步驟Next steps

在此快速入門中,您已瞭解如何使用 Xamarin 應用程式,利用 Entity Framework Core 來存取 SQLite 資料庫。In this getting started you have learned how to use a Xamarin.Forms application to access a SQLite database using Entity Framework Core.

其他與 Xamarin 開發人員相關的 Entity Framework Core 主題:Other Entity Framework Core topics of interest to Xamarin developers: