TobiasBuchholz / Plugin.Firebase

Wrapper around the native Android and iOS Firebase Xamarin SDKs
MIT License
220 stars 49 forks source link

[Question] How to get Firestore document fields that have a dynamic name #159

Closed vhugogarcia closed 1 year ago

vhugogarcia commented 1 year ago

Hello friends,

In order to get the values from a document I usually represent them with a Class, for example:

public sealed class User : IFirestoreObject
{
    [FirestoreDocumentId]
    public string Id { get; set; }

    [FirestoreProperty("email")]
    public string Email { get; set; }
}

However, I'm facing a problem. The name of the keys of the document are dynamically added based on some specific values set by an admin to a user. It's easy to obtain the key names from the document, but since I can't dynamically add class members to the Class how can I obtain their corresponding values?

I have tried the following approaches without luck:

// Try #1
var documentReference = CrossFirebaseFirestore.Current.GetDocument(path);
var document = await documentReference.GetDocumentSnapshotAsync<Dictionary<object, object>>();

// Try #2
var documentReference = CrossFirebaseFirestore.Current.GetDocument(path);
var document = await documentReference.GetDocumentSnapshotAsync<dynamic>();

// Try #3
var documentReference = CrossFirebaseFirestore.Current.GetDocument(path);
var document = await documentReference.GetDocumentSnapshotAsync<object>();

If I set dynamic I can see the data returned on the local watch, however, I'm unable to parse them or convert it to a Dictionary.

image

if I try to parse it with the following code: user.info = (IList<string>)document.Data["clusters"]; I get an error where it is unable to cast the data.

Any recommendation or hint is always welcome

Thanks in advance

vhugogarcia commented 1 year ago

I was able to solve this issue by using a different approach when storing data in Firebase CloudFirestore.

I'm closing this issue.

Thank you!