使用Firebase数据库处理事务和数组

时间:2018-12-15 17:57:29

标签: c# firebase unity3d firebase-realtime-database

我正在使用save data as transactions保存排行榜数据

我正在寻找一种方法来删除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);
    }

实时数据库示例: enter image description here

1 个答案:

答案 0 :(得分:0)

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
Transaction Operations 相类似的REST,可根据特定条件更新数据。请参阅工作流程,并在“保存数据”中了解有关REST的条件请求的更多信息。”可以在https://firebase.google.com/docs/database/rest/save-data#section-conditional-requests上找到
希望对您有所帮助。