首页 > 解决方案 > Azure 移动离线同步:无法从 __operations 中删除操作

问题描述

我有一个大问题,我已经尝试了好几天才能解决。我有一个场景,我试图在我的 Xamarin 项目中处理插入冲突。问题是 Cloud DB 中的记录不存在,因为外键约束存在问题,所以我处于同步冲突处理程序需要删除本地记录以及 __operations 中的记录的情况SQLite 中的表。我什么都试过。将覆盖设置为“true”进行清除,以便它应该删除本地记录和所有关联的操作。不工作。我一直试图通过手动访问 SQL 存储来强制删除它:

var id = localItem[MobileServiceSystemColumns.Id];
var operationQuery = await store.ExecuteQueryAsync("__operations", $"SELECT * FROM __operations WHERE itemId = '{id}'", null).ConfigureAwait(false);
var syncOperation = operationQuery.FirstOrDefault();
var tableName = operation.Table.TableName;

await store.DeleteAsync(tableName, new List<string>(){ id.ToString() });

if (syncOperation != null)
{
    await store.DeleteAsync("__operations", new List<string>() { syncOperation["id"].ToString() }).ConfigureAwait(false);
}

我可以查询 __operations 表,并且可以看到要删除的项目的 ID。DeleteAsync 方法无异常运行,但没有返回任何状态,所以我不知道这是否有效。当我尝试再次同步时,该操作顽固地存在。这看起来很荒谬。如何只删除操作而无需与 Web 服务同步?我将进一步挖掘并尝试通过使用 SQLiteRaw 库来更加努力地强制它,但我真的很希望我错过了一些明显的东西?任何人都可以帮忙吗?谢谢!

标签: azure-mobile-services

解决方案


您需要有一个 Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceSyncHandler 类的子类,它会覆盖 OnPushCompleteAsync() 以处理冲突和其他错误。让我们调用类 SyncHandler:

public class SyncHandler : MobileServiceSyncHandler
{
    public override async Task OnPushCompleteAsync(MobileServicePushCompletionResult result)
    {
        foreach (var error in result.Errors)
        {
            await ResolveConflictAsync(error);
        }
        await base.OnPushCompleteAsync(result);
    }

    private static async Task ResolveConflictAsync(MobileServiceTableOperationError error)
    {
        Debug.WriteLine($"Resolve Conflict for Item: {error.Item} vs serverItem: {error.Result}");

        var serverItem = error.Result;
        var localItem = error.Item;

        if (Equals(serverItem, localItem))
        {
            // Items are the same, so ignore the conflict
            await error.CancelAndUpdateItemAsync(serverItem);
        }
        else // check server item and local item or the error for criteria you care about
        {
            // Cancels the table operation and discards the local instance of the item.
            await error.CancelAndDiscardItemAsync();
        }
    }
}

在初始化 MobileServiceClient 时包含此 SyncHandler() 的实例:

        await MobileServiceClient.SyncContext.InitializeAsync(store, new SyncHandler()).ConfigureAwait(false);

阅读MobileServiceTableOperationError以查看您可以处理的其他冲突以及允许解决它们的方法。


推荐阅读