英文:
Change the document's unique ID from string to int in firebase realtime using xamarin form
问题
我的问题是我想在Firebase实时数据库中将文档/表的唯一ID从字符串更改为整数。
这是我的数据库中的样子:
。
我想要它看起来像这样:
。
这是我插入数据到Firebase的代码:
public async Task<bool> Save(CUSTOMER customer)
{
var token = await authProvider.CreateUserWithEmailAndPasswordAsync(customer.CusEmail, customer.CusPassword);
var data = await firebaseClient.Child(nameof(CUSTOMER)).PostAsync(JsonConvert.SerializeObject(customer));
if (!string.IsNullOrEmpty(data.Key) && !string.IsNullOrEmpty(token.FirebaseToken))
{
return true;
}
return false;
}
英文:
My problem is I want to change the document/table unique ID from string to int in firebase realtime database.
This is how it looks in my database:
.
I want to look like this:
.
This is my code in inserting data to firebase:
public async Task<bool> Save(CUSTOMER customer)
{
//var token = await authProvider.CreateUserWithEmailAndPasswordAsync(customer.CusEmail,customer.CusPassword);&& !string.IsNullOrEmpty(token.FirebaseToken);
var token = await authProvider.CreateUserWithEmailAndPasswordAsync(customer.CusEmail, customer.CusPassword);
var data = await firebaseClient.Child(nameof(CUSTOMER)).PostAsync(JsonConvert.SerializeObject(customer));
if (!string.IsNullOrEmpty(data.Key) && !string.IsNullOrEmpty(token.FirebaseToken))
{
return true;
}
return false;
}
答案1
得分: 0
当您调用PostAsync
时,Firebase会为该数据创建一个带有独特ID的新子节点。这些ID始终具有您在第一张截图中看到的形式,无法更改。
要指定自己的ID,请在客户端应用程序代码中生成该ID,将其作为附加的Child()
调用传递给API,并使用Put
而不是Post
。例如:
firebaseClient.Child(nameof(CUSTOMER)).Child("4815").PutAsync(JsonConvert.SerializeObject(customer));
如果您要使用的数字基于数据库中的现有键,您将需要使用事务来执行必要的读取-写入序列。
由于您考虑使用数字键,我建议查看Firebase中的最佳实践:数组。
英文:
When you call PostAsync
, Firebase creates a new child node with its own unique ID for that data. The IDs always have the form that you see in your first screenshot, and there's no way to change that.
To specify your own ID, generate that ID in your client-side application code, pass it to the API as an additional Child()
call, and use Put
instead of Post
. For example:
firebaseClient.Child(nameof(CUSTOMER)).Child("4815").PutAsync(JsonConvert.SerializeObject(customer));
If the number you want to use is based on the existing keys in the database, you'll need to use a transaction to perform the necessary read-then-write sequence.
Since you're considering using numeric keys, I recommend checking out Best Practices: Arrays in Firebase.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论