![](/img/trans.png)
[英]What is the most efficient way to get all documents from multiple sub-collections of multiple sub-collections in Firestore?
[英]Get Collections and sub collection of documents
我需要獲取 Firestore 集合中所有文檔的集合及其子集合。
如果我要創建它的 json,它將如下所示
{
"Plazas": {
"Doc.Id": "Plaza1"
"NumberOfLanes": 4,
"PlazaName": "My Plaza Name"
"ServerIp": "127.0.0.1"
"Lanes": {
"Doc.Id": "Lane1",
"IpAddress": "127.0.0.2",
"IsExit": true,
"Softwares": {
"Doc.Id": "Software1",
"LastUpdate": "2022-01-01",
"Version": 1.0.0.0
}
}
}
}
這些是我的課程:
[FirestoreData]
public class Plaza
{
public string? DocId { get; set; } = null;
[FirestoreProperty]
public int NumberOfLanes { get; set; }
[FirestoreProperty]
public string? PlazaName { get; set; } = null;
[FirestoreProperty]
public string? ServerIp { get; set; } = null;
public DateTime? DateCreated { get; set; }
[FirestoreProperty]
public List<Lane> Lanes { get; set; } = new List<Lane>() { };
}
[FirestoreData]
public class Lane
{
public string? DocId { get; set; } = null;
[FirestoreProperty]
public string? IpAddress { get; set; }
[FirestoreProperty]
public bool IsExit { get; set; }
public List<Software> Softwares { get; set; } = new List<Software> { };
}
[FirestoreData]
public class Software
{
public string? DocId { get; set; } = null;
[FirestoreProperty]
public DateTime? LastUpdate { get; set; }
[FirestoreProperty]
public string? Version { get; set; } = null;
}
這就是我獲取所有數據的方式:
public async Task<List<Plaza>> GetAllPlaza()
{
try
{
var plazaQuery = firestoreDb.Collection("Plazas");
var plazaQuerySnapshot = await plazaQuery.GetSnapshotAsync();
var plazaList = new List<Plaza>();
foreach(var documentSnapshot in plazaQuerySnapshot)
{
if (documentSnapshot.Exists)
{
Dictionary<string, object> plaza = documentSnapshot.ToDictionary();
var json = JsonConvert.SerializeObject(plaza);
var newPlaza = JsonConvert.DeserializeObject<Plaza>(json);
newPlaza.DocId = documentSnapshot.Id;
newPlaza.DateCreated = documentSnapshot.CreateTime.Value.ToDateTime();
plazaList.Add(newPlaza);
}
}
var storedPlazaList = plazaList.OrderBy(x => x.DocId).ToList();
return storedPlazaList;
}
catch (Exception ex)
{
throw;
}
}
在運行時,這是我得到的唯一數據:
{
"PlazaName":"My Plaza Name",
"NumberOfLanes":4,
"ServerIp":"127.0.0.1"
}
當我反序列化時,“車道”屬性計數為 0(因為它無法從 firestore 獲取車道)。
Firestore 上的讀取操作總是很淺,因此如果您的示例數據中的Lanes
是一個子集合,那么確實預計它也不會自動讀取。 在閱讀父文檔后,您需要對Lanes
子集合執行單獨的讀取操作以獲取這些文檔。 您可以從documentSnapshot.Reference.Collection("Lanes")
獲取相關的CollectionReference
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.