I am working with Firebase in .NET MAUI using the firebase-database-dotnet package and need help capturing the node keys (IDs) of the products retrieved from Firebase.
The data structure in Firebase is as follows:
products
product1
category: "dairy"
description: "Sliced Arequipe cheese, ideal for accompanying your meals."
name: "Arequipe Cheese Sliced"
price: 10.99
product10
category: "dairy"
description: "Box of 30 Kikes eggs."
name: "Kikes Eggs 30 pcs"
price: 3.99
I have the following method to retrieve products from Firebase:
public async Task<IEnumerable<T>> GetItemsAsync(bool forceRefresh = false)
{
try
{
var firebaseObjects = await _query
.OnceAsync<T>();
return firebaseObjects
.Select(x => x.Object);// Devuelve los FirebaseObject<T> completos
}
catch (Exception ex)
{
return null;
}
}
This method returns the product objects, but I don’t know how to capture the node keys (product1, product10, etc.).
Now, I want to implement a method to save a selected product in Firebase, and I need to capture the node ID corresponding to the product. For example:
[RelayCommand]
public async Task SaveProduct(Product product)
{
// Here, I want to use the GetItemsAsync method to retrieve the existing products.
// How can I capture the node ID (such as 'product1' or 'product10') of the selected product?
}
Is it possible to include an ID within the table, or is it considered a bad practice? How can I capture the node keys along with the data in my current
Generally speaking, the product1
,product10
,etc. you mentioned are automatically generated.
To update the special item on the products
list, we usually add a field and guarantee that its value is unique.
For example:
public class Product
{
public string Name { get; set; }
//add field ID (it's value is unique)
public string ProductId{ get; set; }
}
Then if we want to update the special product of products
list, we can first iterate through the products list and find the item by the field ID
.
You can refer to the following code snippet:
Product product = new Products();
product.Name = "product18";
if (btnSaveText == "UPDATE")
{
//other code
product.ProductId="xxxxx";
var updateProduct = (await fClient.Child("Products").OnceAsync<Product>()).FirstOrDefault(x => x.Object.ProductId == products.ProductId);
if (updateProduct == null)
{
lblMessage = "Cannot find selected Product";
isBusy = false;
return;
}
await fClient
.Child("Products" + "/" + updateProduct.Key).PatchAsync(JsonConvert.SerializeObject(product));
lblMessage = "Product updated successfully";
}