【问题标题】:Xamarin.Android How can I set the id of an entry to the generated key from a Firebase DatabaseXamarin.Android 如何将条目的 id 设置为从 Firebase 数据库生成的密钥
【发布时间】:2017-08-12 16:15:59
【问题描述】:

我正在尝试将唯一字符串存储在 Firebase 中的我的班级中。

目前我正在创建新类别,如下所示

我的班级:

 public class Category
 {
    public string categoryId { get; set; }
    public string categoryName { get; set; }
    public string uid { get; set; }
    //public List<Photo> photos { get; set; }
}

我的活动:

private async void InsertNewCategory()
    {
        Category categories = new Category();
        categories.categoryName = input_newCategory.Text;

        //get the generated key
        //var categoryid = categories.Key;

        var user = FirebaseAuth.Instance.CurrentUser;

        if (user != null)
        {
            var uid = user.Uid;
            //set the users id to the category
            categories.uid = uid;
        }            

        var firebase = new FirebaseClient(FirebaseURL);
        var item = await firebase.Child("categories").PostAsync(categories);
    } 

这是它在 firebase 数据库中的样子:

我想将 categoryId 设置为生成的键,使其独一无二!这可能吗?如果可以,我可以在创建新项目时这样做吗?

任何帮助将不胜感激。

【问题讨论】:

    标签: android firebase xamarin firebase-realtime-database xamarin.android


    【解决方案1】:

    您可以在实际存储数据之前使用 Push() 获取引用“密钥”并将其用作您的uid

    使用 Push() 获取“新”数据库引用:

    var categoriesRef = firebase.Database.GetReference("categories");
    var newReference = categoriesRef.Push();
    var category = new Category { categoryId = categoriesRef.Key, categoryName = "StackOverflow", uid = newReference.Key };
    await newReference.SetValueAsync(category.Map);
    
    newReference = categoriesRef.Push();
    category = new Category { categoryId = categoriesRef.Key, categoryName = "Rocks", uid = newReference.Key };
    await newReference.SetValueAsync(category.Map);
    

    FireBase 数据库结果:

    {
      "categories" : {
        "-KrMgASSnq41nxWcDc7H" : {
          "categoryId" : "categories",
          "categoryName" : "StackOverflow",
          "uid" : "-KrMgASSnq41nxWcDc7H"
        },
        "-KrMgBNKh1pNSIyg-DoV" : {
          "categoryId" : "categories",
          "categoryName" : "Rocks",
          "uid" : "-KrMgBNKh1pNSIyg-DoV"
        }
      }
    }
    

    【讨论】:

    • @SushilHangover 我收到错误 firebase 不包含数据库的定义?
    • @Smac 是DatabaseReference的成员,即Firebase.Database.FirebaseDatabase.GetInstance("XXXX").Reference.Database
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2017-02-10
    • 2016-08-03
    • 2021-12-30
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多