f-miyu / Plugin.CloudFirestore

MIT License
121 stars 44 forks source link

How to convert a reference #35

Closed KarasuX2 closed 4 years ago

KarasuX2 commented 4 years ago

I´m having an issue converting a reference to another document.

This is my Database. image

image

Code: image

When trying to iterate through the documents I´m getting this error message.

Object of type 'Plugin.CloudFirestore.DocumentReferenceWrapper' cannot be converted to type 'Namespace.OtherObject

f-miyu commented 4 years ago

Reference Type of Firestore is converted to IDocumentReference of Plugin.CloudFirestore. So, you need to get IDocumentSnapshot form this IDocumentReference again. An example is as follows.

public class Object
{
    public int Id { get; set; }
    public IDocumentReference RefToOtherObject { get; set; }
}

public class OtherObject
{
    public string Name { get; set; }
}

public class FireStoreAccess
{
    public async void GetObjectAsync()
    {
        try
        {
            var documents = await CrossCloudFirestore.Current
                                                .Instance
                                                .GetCollection("Object")
                                                .GetDocumentsAsync();

            var doc = documents.ToObjects<Object>();
            var otherObjectDocs = await Task.WhenAll(doc.Select(x => x.RefToOtherObject.GetDocumentAsync()));
            var otherObjects = otherObjectDocs.Select(x => x.ToObject<OtherObject>());
            foreach (OtherObject o in otherObjects)
            {
                Console.WriteLine(o.Name);
            }
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
KarasuX2 commented 4 years ago

Thank you very much.

var query = await CrossCloudFirestore.Current .Instance .GetCollection("Object") .WhereEqualsTo("RefToOtherObject", OtherObjectRef.Id) .GetDocumentsAsync();

Is there a way to just get the Objects with the specific References? I tried the above source code, but I´m just recieving an empty list.

f-miyu commented 4 years ago

It will work if you use OtherObjectRef instead of OtherObjectRef.Id for WhereEqualsTo.

var query = await CrossCloudFirestore.Current
.Instance
.GetCollection("Object")
.WhereEqualsTo("RefToOtherObject", OtherObjectRef)
.GetDocumentsAsync();
KarasuX2 commented 4 years ago

Easier than I thought. Thank you very much.