首页 > 解决方案 > 使用 Firebase 数据库处理事务和数组

问题描述

我正在使用将数据保存为事务来保存排行榜数据

我正在寻找一种方法来使用 Firebase 事务删除数组编号并将其替换userId为以便我能够更新用户信息。代码:

 private TransactionResult AddScoreTransaction(MutableData mutableData)
    {
        playerNewGlobalScore = false;
        List<object> leaders = mutableData.Value as List<object>;
        if (leaders == null)
        {
            leaders = new List<object>();
        }
        else if (mutableData.ChildrenCount >= LeaderBoardManager.Instance.MaxScoreRows)
        {
            // If the current list of scores is greater or equal to our maximum allowed number,
            // we see if the new score should be added and remove the lowest existing score.
            long minScore = long.MaxValue;
            object minVal = null;

            foreach (var child in leaders)
            {
                if (!(child is Dictionary<string, object>))
                    continue;
                long childScore = (long)((Dictionary<string, object>)child)["score"];
                if (childScore < minScore)
                {
                    minScore = childScore;
                    minVal = child;
                }
            }
            // If the new score is lower than the current minimum, we abort.
            if (minScore > Score)
            {
                return TransactionResult.Abort();
            }
            // Otherwise, we remove the current lowest to be replaced with the new score.

            leaders.Remove(minVal);
        }

        // Now we add the new score as a new entry that contains the email address and score.
        Dictionary<string, object> newScoreMap = new Dictionary<string, object>();

        newScoreMap["name"] = Name;
        newScoreMap["country"] = Country;
        newScoreMap["photoUrl"] = PhotoUrl;
        newScoreMap["level"] = Level;
        newScoreMap["userId"] = UserId;
        newScoreMap["score"] = Score;

        leaders.Add(newScoreMap);

        // You must set the Value to indicate data at that location has changed.
        mutableData.Value = leaders;

        playerNewGlobalScore = true;
        return TransactionResult.Success(mutableData);
    }

实时数据库示例: 在此处输入图像描述

标签: c#firebaseunity3dfirebase-realtime-database

解决方案


https://cloud.google.com/support#support-plans Firebase 不支持 C#,他们对此很满意(参见https://stackshare.io/stackups/firebase-vs-pusher-vs-signalr),firestore做。他们建议您访问https://groups.google.com/forum/#!forum/firebase-talk
但是 来自 Step Up Labs, Inc的https://github.com/step-up-labs/firebase-database-dotnet . (使用 NuGet Firebase)对于您想要通过 REST API https://firebase.google.com/docs/reference/rest/database
执行的所有操作很有用 在文档的底部是“条件请求, SDK
事务操作的 REST 等价物,根据一定的条件更新数据。查看工作流程概述并了解有关保存数据中 REST 的条件请求的更多信息。”可以在https://firebase.google.com/docs/database/rest/save-data#section-conditional-requests
找到希望这会有所帮助。


推荐阅读