TobiasBuchholz / Plugin.Firebase

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

Firestore - Object of type 'System.Int64' cannot be converted to type 'System.Int32' #99

Closed arahmancsd closed 1 year ago

arahmancsd commented 1 year ago

I have the followings to get, add, and update data in Firestore, however, it seems somewhere in the wrapper it doesn't cast int64 to int32 or vice versa while the model itself doesn't contain long or Int64.

public class Post : IFirestoreObject
{
    [FirestoreProperty("id")]
    public int Id { get; set; }
    [FirestoreProperty("likesCount")]
    public int LikesCount { get; set; }
}

private async Task ModifyPostAsync()
    {
        try
        {
            var post = new Post() { Id = 1, LikesCount = 1 };
            string collectionName = nameof(Post).ToLower();

            var querySnapshot = await _firebaseFirestore.GetCollection(collectionName)
                .WhereEqualsTo("id", post.Id)
                .LimitedTo(1)
                .GetDocumentsAsync<Post>();

            if (querySnapshot.IsEmpty)
            {
                post.LikesCount = 1;
                await _firebaseFirestore.GetCollection(collectionName).GetDocument(post.Id.ToString()).SetDataAsync(post);
            }
            else
            {
                var doc = querySnapshot.Documents.FirstOrDefault(); // getting error in this line
                var likeCounts = doc.Data.LikesCount + 1;

                Dictionary<object, object> parameters = new()
                {
                    {"likesCount", likeCounts }
                };

                await _firebaseFirestore.GetCollection(collectionName).GetDocument(post.Id.ToString()).UpdateDataAsync(parameters);
            }
        }
        catch (Exception ex)
        {
            _firebaseCrashlyticsService.Log(ex);
        }
Screenshot 2022-12-04 at 23 24 57
TobiasBuchholz commented 1 year ago

Because of internal reasons the plugin only supports properties with the type long, so you'll need to change the Id and LikesCount from int to long:

public class Post : IFirestoreObject
{
    // change from int to long

    [FirestoreProperty("id")]
    public long Id { get; set; }
    [FirestoreProperty("likesCount")]
    public long LikesCount { get; set; }
}
arahmancsd commented 1 year ago

Thanks, long solved the issue.