Exemple #1
0
        private static async Task ReturnInfoTransaction(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_return_info_transaction]
            DocumentReference cityRef = db.Collection("cities").Document("SF");
            bool transactionResult    = await db.RunTransactionAsync(async transaction =>
            {
                DocumentSnapshot snapshot = await transaction.GetDocumentSnapshotAsync(cityRef);
                long newPopulation        = snapshot.GetField <long>("Population") + 1;
                if (newPopulation <= 1000000)
                {
                    Dictionary <FieldPath, object> updates = new Dictionary <FieldPath, object>
                    {
                        { new FieldPath("Population"), newPopulation }
                    };
                    transaction.Update(cityRef, updates);
                    return(true);
                }
                else
                {
                    return(false);
                }
            });

            if (transactionResult)
            {
                Console.WriteLine("Population updated successfully.");
            }
            else
            {
                Console.WriteLine("Sorry! Population is too big.");
            }
            // [END fs_return_info_transaction]
        }
Exemple #2
0
        private static async Task RunSimpleTransaction(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_run_simple_transaction]
            DocumentReference cityRef = db.Collection("cities").Document("SF");
            await db.RunTransactionAsync(async transaction =>
            {
                DocumentSnapshot snapshot = await transaction.GetDocumentSnapshotAsync(cityRef);
                long newPopulation        = snapshot.GetField <long>("Population") + 1;
                Dictionary <FieldPath, object> updates = new Dictionary <FieldPath, object>
                {
                    { new FieldPath("Population"), newPopulation }
                };
                transaction.Update(cityRef, updates);
            });

            // [END fs_run_simple_transaction]
            Console.WriteLine("Ran a simple transaction to update the population field in the SF document in the cities collection.");
        }