获取文档的集合和子集合

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