step-up-labs / firebase-database-dotnet

C# library for Firebase Realtime Database.
MIT License
671 stars 170 forks source link

Assign generated key to the property (ID) #266

Closed L10Messi10 closed 2 years ago

L10Messi10 commented 2 years ago

Thank you for this package.

Anyway, I have been boggling my mind in this past few weeks trying to figure out how to assign the generated key to the ID 1

As you can see above the red one must be the same as the yellow one. I have achieved such by doing this.. 2

As you can see, my code above is embarrassing 😅, it Post first, then get the key, then post again, then delete that. To clarify it more, I can't get the generated key at the first Post, so I have to Post first to get the key then Post again to save the key, then finally delete it so it won't double the record.

Now my question is, how can we get the same key with only one Post?

cabauman commented 2 years ago

I don't think there's a straightforward way to achieve that. However, the FirebaseKeyGenerator class is public, so you can use that together with PutAsync. PostAsync does it this way internally if the generateKeyOffline argument is set to true, so there should be no concerns about doing it this way.

L10Messi10 commented 2 years ago

Thank you for the response, does the key generated guarantee uniqueness of the key??

cabauman commented 2 years ago

The FirebaseKeyGenerator source code says that it mimics the official Firebase generators, so I would say collisions are extremely unlikely.

If you still prefer post over put, just follow up that first PostAsync call with PatchAsync or PutAsync to overwrite the Id field. Then you won't have to do that third DeleteAsync step.

L10Messi10 commented 2 years ago

Update about the issue, PatchAsync actually didn't solve the issue but it gives me the idea to retrieve the generated ID and finally use the PutAsync (Update) to actually update the node. Here is the full codes below.

var _users= await firebaseClient.Child("Users").PostAsync(new Users
             {
                MyProperty = recorddata.Text
             });
            await firebaseClient.Child("Users")
                .Child(_users.Key)
                .PutAsync(new Users
            {
                Id = _users.Key,
                MyProperty = recorddata.Text
            });

4

As you can see, the Id is now the same as the generated Firebase ID.