将脱机数据同步添加到 .NET MAUI 应用

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://learn.microsoft.com/zh-cn/azure/developer/mobile-apps/azure-mobile-apps/quickstarts/maui/offline?pivots=vs2022-windows

本教程介绍适用于 .NET MAUI 的 Azure 移动应用的脱机同步功能。 脱机同步允许最终用户与移动应用交互,即使没有网络连接也是如此。 更改存储在本地数据库中。 设备重新联机后,这些更改会与远程后端同步。

在开始本教程之前,应已完成 .NET MAUI 快速入门教程,其中包括创建合适的后端服务。

更新应用以支持脱机同步

在联机操作中,可以对 IRemoteTable<T> 进行读取和写入。 使用脱机同步时,可以对 IOfflineTable<T> 进行读取和写入。 IOfflineTable 由设备上的 SQLite 数据库提供支持,与后端数据库进行同步。

在 Visual Studio 中:

  1. 右键单击解决方案 TodoApp ,然后选择“ 管理解决方案的 NuGet 包...”

  2. 在新选项卡中,选择“ 浏览”,然后在搜索框中输入 Microsoft.Datasync.Client


  3. 选择 Microsoft.Datasync.Client.SQLiteStore 包。

  4. 在右侧窗格中,选择除项目) 之外 TodoAppService.NET6 的所有客户端项目 (。

  5. 选择“安装” 。

  6. 出现提示时接受许可协议。

在 Visual Studio 中:

  1. 右键单击解决方案 TodoApp ,然后选择“ 管理 NuGet 包...”

  2. 选择“ 浏览 ”选项卡,然后在搜索框中输入 Microsoft.Datasync.Client


  3. 选择 Microsoft.Datasync.Client.SQLiteStore 包。

  4. 选择“添加包”。

  5. “选择项目” 窗口中,选择除项目) 之外 TodoAppService.NET6 的所有客户端项目 (。

  6. 选择“确定” 。

  7. 出现提示时接受许可协议。

更新远程服务客户端

打开TodoApp.Data项目并在目录) Services中找到RemoteTodoService.cs类 (。 按如下所示更新 类:

  1. 将下面的 using 语句添加到文件顶部:

    using Microsoft.Datasync.Client.SQLiteStore;
    
  2. 将 的定义 _table 更改为 IOfflineTable<TodoItem>

    /// <summary>
    /// Reference to the table used for datasync operations.
    /// </summary>
    private IOfflineTable<TodoItem> _table = null;
    
  3. 添加用于存储脱机数据库位置的新属性:

    /// <summary>
    /// The path to the offline database
    /// </summary>
    public string OfflineDb { get; set; }
    
  4. InitializeAsync更新 方法以定义脱机数据库:

    // Create the offline store definition
    var connectionString = new UriBuilder { Scheme = "file", Path = OfflineDb, Query = "?mode=rwc" }.Uri.ToString();
    var store = new OfflineSQLiteStore(connectionString);
    store.DefineTable<TodoItem>();
    var options = new DatasyncClientOptions
    {
        OfflineStore = store,
        HttpPipeline = new HttpMessageHandler[] { new LoggingHandler() }
    };
    
    // Create the datasync client.
    _client = TokenRequestor == null 
        ? new DatasyncClient(Constants.ServiceUri, options)
        : new DatasyncClient(Constants.ServiceUri, new GenericAuthenticationProvider(TokenRequestor), options);
    
    // Initialize the database
    await _client.InitializeOfflineStoreAsync();
    
    // Get a reference to the offline table.
    _table = _client.GetOfflineTable<TodoItem>();
    
    // Set _initialized to true to prevent duplication of locking.
    _initialized = true;
    
  5. RefreshItemsAsync()更新 以执行脱机同步:

    /// <summary>
    /// Refreshes the TodoItems list manually.
    /// </summary>
    /// <returns>A task that completes when the refresh is done.</returns>
    public async Task RefreshItemsAsync()
    {
        await InitializeAsync();
    
        // First, push all the items in the table.
        await _table.PushItemsAsync();
    
        // Then, pull all the items in the table.
        await _table.PullItemsAsync();
    
        return;
    }
    

设置脱机数据库位置

TodoApp.MAUI 项目中,编辑 MainPage.xaml.cs 文件。 更改 的定义, RemoteTodoService 如下所示:

TodoService = new RemoteTodoService(GetAuthenticationToken)
{
    OfflineDb = FileSystem.CacheDirectory + "/offline.db"
};

如果尚未完成 身份验证教程,则定义应如下所示:

TodoService = new RemoteTodoService()
{
    OfflineDb = FileSystem.CacheDirectory + "/offline.db"
};

测试应用程序

在按下刷新图标之前,应用不会与后端同步。 测试:

  1. 打开 Azure 门户

  2. 打开包含快速入门资源的资源组。

  3. 选择 quickstart 数据库。

  4. 选择 查询编辑器 (预览)

  5. 使用为数据库设置的相同凭据使用 SQL Server 身份验证登录。

    • 如有必要,系统会提示你允许访问你的 IP 地址。 选择链接以更新允许列表,然后按 “确定” 重试登录。
  6. 在查询编辑器中输入 SELECT * FROM [dbo].[TodoItems]。 然后,选择“运行”。

将显示当前 TodoItems 的列表。


现在,通过应用进行一些更改。 请勿按刷新 () 。

重复Azure 门户中的 SQL 语句,并验证是否未对数据库中的数据进行更改。

选择应用上的 “刷新” 图标,将队列中的数据推送到后端服务。 你将在“输出调试”窗口中看到正在发生的 HTTP 事务。

重复Azure 门户中的 SQL 语句,并验证是否已将更改推送到远程服务。