You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore数据转C#对象失败:Devices属性为空问题求助

Firestore中User对象Devices属性映射为空的解决方法

问题出在C#类与Firestore数据结构不匹配:你的Firestore里Devices是键值对形式的Map结构(以设备ID为键,对应Device对象为值),但之前用的Dictionary<string, object>无法自动完成强类型转换,List<Device>则对应Firestore的数组结构,和你的数据模型完全不符,所以导致Devices始终为空。

修正后的User类定义

把User类中的Devices属性改为Dictionary<string, Device>,让Firestore SDK直接将Map中的值映射为Device强类型对象:

namespace GoogleCloudFirestoreDemo.Model
{
    [FirestoreData]
    public class User
    {
        [FirestoreProperty]
        public Name Name { get; set; }

        [FirestoreProperty]
        public string Email { get; set; }

        // 改为Dictionary<string, Device>,匹配Firestore的Map结构
        [FirestoreProperty]
        public Dictionary<string, Device> Devices { get; set; }
    }
}

为什么之前的写法不行?

  • Dictionary<string, object>:Firestore SDK不会自动将object类型转换为自定义的Device类,需要手动处理类型转换,并非最优解。
  • List<Device>:这个类型对应Firestore的数组(Array)结构,但你的数据是Map(键值对),结构不匹配,无法完成映射。

验证代码

保持原有查询代码不变,现在转换后user.Devices会正确包含Firestore中的所有设备数据:

DocumentReference docRef = db.Document("users/XKJxMfQ1rmmf873vzGof");
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();

if (snapshot.Exists)
{
    Model.User user = snapshot.ConvertTo<Model.User>();
    // 此时user.Devices已正确映射数据
}

内容的提问来源于stack exchange,提问作者yonan2236

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:03:21