How to get Firestore document fields that have a dynamic name

203 views Asked by At

I use Plugin.CloudFirestore

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

public class FirestoreDoc
{
    public string key { get; set; }
}

firestoreDoc.ToObject<FirestoreDoc>().key;

Right now I have a specific problem. The name of the keys of the document are dynamically added by the user of the app. 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?

edit:

Some additional information.

The fields I try to get are of type array and they store reference to other database documents.

Here is what I tried:

var referenceList = firestoreDoc.Data[customKey];

With that line I succeed to get the value of the specific key, but I still have two issues:

  • I can't iterate over the values of the list I get,
  • The values of the List are of type string and not IDocumentReference so I can't call the GetAsync() method on them to get the referenced documents.

For the second issue I tried a cast:

var referenceList = (List<IDocumentReference>)firestoreDoc.Data[customKey];

but the result of the cast is an error: System.InvalidCastException: 'Specified cast is not valid.'

1

There are 1 answers

4
Costas On BEST ANSWER

Well, after trying different approaches here is the solution:

var referenceList = (IEnumerable<Object>)firestoreDoc.Data[customKey];

foreach (var reference in referenceList)
{
     var referredDoc = await ((IDocumentReference)reference).GetAsync();
}