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.

提示

可在 GitHub 示例中查看此文章的示例。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 或 Visual Studio for Mac 中打开解决方案文件 EFGettingStarted.sln,并在所选平台上运行应用程序。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 数据库(其中包含两个表示博客的条目)。When the app first starts, it will populate the local SQLite database with two entries representing blogs.

包含所有博客的列表页的屏幕截图

单击工具栏中的“添加”按钮。Click the Add button in the toolbar.

随即将显示一个新的页面,你可在该页面输入新博客的相关信息。A new page will appear that allows you to enter information about a new blog.

新博客编辑页的屏幕截图

填写所有信息,然后单击工具栏中的“保存”。Fill out all the info and click Save from the toolbar. 新博客将保存到应用的 SQLite 数据库中,并显示在列表中。The new blog will save to the app's SQLite database and will show in the list.

你可单击列表中的一个博客条目,并查看该博客的任何帖子。You can click on one of the blog entries in the list and see any posts for that blog.

博客文章列表页的屏幕截图

在工具栏中,单击“添加”。Click Add in the toolbar.

此时将显示一个页面,你可在该页面中填写新博客文章的相关信息。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.

新文章将与上一步中单击的博客文章关联,它将保存到应用的 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.

返回到博客列表页。Go back to the blog list page. 然后单击工具栏中的“全部删除”。And click Delete All in the toolbar. 所有博客及其对应的文章随后都将从应用的 SQLite 数据库中删除。All blogs and their corresponding posts will then be deleted from the app's SQLite database.

博客被全部删除的应用的屏幕截图

浏览代码Explore the code

以下各部分将展示示例项目中的代码,该项目会搭配 EF Core 使用 Xamarin.Forms 从 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 NuGet 包Entity Framework Core NuGet packages

若要使用 EF Core 创建 Xamarin. Forms 应用,请将要以其为目标的 EF Core 数据库提供程序的包安装到 Xamarin.Forms 解决方案中的所有项目。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.Forms 解决方案的每个项目中都需要以下 NuGet 包。The following NuGet package is needed in each of the projects in the Xamarin.Forms solution.

  • Microsoft.EntityFrameworkCore.Sqlite

模型类Model classes

通过 EF Core 访问的 SQLite 数据库中的每个表都在某个类中进行建模。Each table in the SQLite database accessed through EF Core is modeled in a class. 在本例中使用了两个类 - BlogPost,它们位于 Models 文件夹。In 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 属性会定义 BlogPost 之间的父子关系。The 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 属性与 Post 的实例的父级 Blog 对象相关联。The 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 类中的两个属性都用于对表示博客和文章的基础表进行操作。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.
    • BlogsPage.xaml.csOnAppearing 函数可返回所有 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.
    • PostsPage.xaml.csOnAppearing 函数可返回包含特定 BlogIdPost 记录。The 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.
    • AddBlogPage.xaml.csSave_Clicked 函数可将新的 Blog 对象插入到 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.
    • AddPostPage.xaml.csSave_Clicked 函数使用新的 Post 更新现有的 Blog 对象。The 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

  • 删除所有记录并级联删除其子记录。Delete all records with cascade to child records.
    • BlogsPage.xaml.csDeleteAll_Clicked 函数可删除 SQLite 数据库中的所有 Blog 记录,并级联删除 Blog 的所有 Post 子记录。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.Forms 应用程序通过 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: