開始使用EF Core和 Xamarin

在本教學課程中,您會建立 Xamarin.Forms 應用程式,以使用 Entity Framework Core 對 SQLite 資料庫執行數據存取。

您可以在 Windows 或 Visual Studio for Mac 上使用 Visual Studio 來遵循本教學課程。

提示

您可以檢視本文中的 GitHut 範例

必要條件

安裝下列其中一項:

檔提供每個平台的詳細逐步安裝指示

下載並執行範例專案

若要執行並探索此範例應用程式,請在 GitHub 上下載程式代碼。

下載之後,請在 Visual Studio 或 Visual Studio for Mac 中開啟方案檔 EFGettingStarted.sln ,然後在您選擇的平臺上執行應用程式。

當應用程式第一次啟動時,它會以代表部落格的兩個專案填入本機 SQLite 資料庫。

Screenshot of all blogs list page

按兩下工具列中的 [ 新增 ] 按鈕。

隨即會出現新的頁面,可讓您輸入新部落格的相關信息。

Screenshot of new blog edit page

填寫所有資訊,然後按兩下工具列中的 [ 儲存 ]。 新的部落格會儲存至應用程式的 SQLite 資料庫,並顯示在清單中。

您可以按下清單中的其中一個部落格專案,並查看該部落格的任何文章。

Screenshot of blog posts list page

按兩下 工具列中的 [新增 ]。

接著會出現一個頁面,可讓您填寫新部落格文章的相關信息。

Screenshot of add new post page

填寫所有資訊,然後按兩下工具列中的 [ 儲存 ]。

新文章會與您在上一個步驟中按兩下的部落格文章相關聯,並將儲存至應用程式的 SQLite 資料庫,並顯示在清單中。

返回部落格清單頁面。 然後按下工具列中的 [ 全部 刪除]。 然後,所有部落格及其對應的文章都會從應用程式的 SQLite 資料庫中刪除。

Screenshot of app with all blogs deleted

探索程式碼

下列各節將逐步引導您在範例專案中使用 EF Core 搭配 Xamarin.Forms 讀取、建立、更新和刪除 SQLite 資料庫中的程式代碼。

假設您已熟悉顯示數據的 Xamarin.Forms 主題,並在頁面之間流覽。

重要

Entity Framework Core 會使用反映來叫用 Xamarin.iOS 連結器在發行模式設定中可能會去除的函式。 您可以透過兩種方式之一來避免這種情況。

  • 第一個是新增--linkskip System.CoreiOS 組建選項中的 [其他 mtouch] 自變數
  • 或者,將 iOS 組建選項中的 Xamarin.iOS 連結器行為設定為 Don't Link 本文說明 Xamarin.iOS 連結器 的詳細資訊,包括如何在 Xamarin.iOS 上設定行為。 (這種方法並不理想,因為它可能會導致商店拒絕)。

Entity Framework Core NuGet 套件

若要使用 EF Core 建立 Xamarin.Forms 應用程式,您要將 EF Core 資料庫提供者的套件安裝到 Xamarin.Forms 解決方案中的所有專案。 本教學課程使用 SQLite 提供者。

Xamarin.Forms 解決方案中的每個專案都需要下列 NuGet 套件。

  • Microsoft.EntityFrameworkCore.Sqlite

模型類別

透過EF Core 存取之 SQLite 資料庫中的每個數據表都會在類別中建立模型。 在此範例中,會使用兩個類別: Blog 您可以在 Post 資料夾中找到 Models 這兩個類別。

模型類別只由資料庫中的模型數據行所組成。

  • Blog.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會定義 與Post之間的Blog父子關聯性。

  • Post.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 屬性會回到 實例的PostBlog物件。

資料內容

類別 BloggingContext 位於資料夾中, Services 繼承自EF Core DbContext 類別。 DbContext用來將資料庫查詢和變更分組在一起。

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 這兩個屬性都用來在代表部落格和貼文的基礎表上操作。
  • SQLitePCL.Batteries_V2.Init()建構函式中需要 ,才能在iOS上起始SQLite。
  • OnConfiguring 式會設定實體裝置上 SQLite 資料庫的位置。

建立、讀取、更新及刪除

以下是 EF Core 用來存取 SQLite 之應用程式中的一些實例。

參閱

  • 傳回所有記錄。
    • BlogsPage.xaml.csOnAppearing式會傳回所有Blog記錄,並將其儲存到List變數中。
using (var blogContext = new BloggingContext())
{
    var theBlogs = blogContext.Blogs.ToList();
}
  • 傳回特定記錄。
    • PostsPage.xaml.csOnAppearing式會傳Post回包含特定 BlogId的記錄。
using (var blogContext = new BloggingContext())
{
    var postList = blogContext.Posts
        .Where(p => p.BlogId == BlogId)
        .ToList();
}

建立

  • 插入新記錄。
    • AddBlogPage.xaml.csSave_Clicked式會將新的 Blog 物件插入 SQLite 資料庫。
var blog = new Blog { Url = blogUrl.Text };

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

    await blogContext.SaveChangesAsync();
}

更新

  • 更新現有的記錄。
    • AddPostPage.xaml.csSave_Clicked式會使用新的 Post來更新現有的 Blog 物件。
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();
}

刪除

  • 刪除具有串聯至子記錄的所有記錄。
    • BlogsPage.xaml.csDeleteAll_Clicked式會刪除 SQLite 資料庫中的所有Blog記錄,並將刪除串連至所有BlogPost記錄。
using (var blogContext = new BloggingContext())
{
    blogContext.RemoveRange(blogContext.Blogs);

    await blogContext.SaveChangesAsync();
}

下一步

在本快速入門中,您已瞭解如何使用 Xamarin.Forms 應用程式,以使用 Entity Framework Core 存取 SQLite 資料庫。

Xamarin 開發人員感興趣的其他 Entity Framework Core 主題: