ums2026
ums2026

Reputation: 147

How to get all child values nested under a parent node in firebase database c#

I am making a Xamarin Forms app (c#) using Firebase Database to store data. I am trying to get all of the child node data from this tree:

Users:

So essentially, getting the values "User 1" and "User 2" in this case. How would this be possible? I know that it is possible to get the "User name" and "User email" if you know what the User 1 value is, but how would I do this to get the child node name while maintaining this data structure?

Please let me know if there is something that I need to clarify or be more specific about.

Upvotes: 0

Views: 852

Answers (1)

Shaw
Shaw

Reputation: 929

Step 1, a local model class:

    public class User
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }

Step 2, a helper class:

    public static class FirebaseHelper
    {
        FirebaseClient firebase = new FirebaseClient("<YOUR_CONNECTION_STRING>");

        public async Task<List<User>> GetAllUsers()
        {
            return (await firebase
              .Child("Users")
              .OnceAsync<User>())
              .Select(item => new User
              {
                  Name  = item.Object.name,
                  Email = item.Object.email
              }).ToList();
        }
    }

Step 3, fetch the list:

    var userList = await FirebaseHelper.GetAllUsers();

Update for fetching the node name

Step 1, a local model class:

    public class User
    {
        public string UserID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

Step 2, the method in the helper class:

    public async Task<List<User>> GetAllUsers()
    {
        return (await firebase
          .Child("Users")
          .OnceAsync<User>())
          .Select(item => new User
          {
              UserID = item.Key,    //the node name is here
              Name   = item.Object.name,
              Email  = item.Object.email
          }).ToList();
    }

Upvotes: 1

Related Questions