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

Xamarin项目中ParseObject子类获取关联ParseUser字段报错如何解决?

问题根源

你遇到的报错由两个核心问题导致:

  1. Parse 查询关联对象时默认仅返回指针数据,不会自动拉取关联对象的自定义字段
    你查询Stuff_ParseBeacon时,返回的SentBy属性只有objectId、className这几个指针基础属性,phoneNumber字段根本没有从服务端同步到本地的ParseUser实例中,自然会报键不存在的错误。
  2. 现有自定义属性不符合可绑定属性的要求
    你写的SentByPhoneNumber没有属性变更通知逻辑,也没有标记忽略同步,既会触发Parse的同步校验,也没法正常和UI绑定。

解决方案

步骤1:修改自定义Parse子类代码

添加[Ignore]标记避免Parse尝试将该字段同步到服务端,补充空值判断避免空引用,同时增加属性变更通知逻辑适配绑定需求:

[ParseClassName("Beacon")]
public class Stuff_ParseBeacon : ParseObject
{
    public Stuff_ParseBeacon() {  }
    
    [ParseFieldName("sentBy")]
    public ParseUser SentBy
    {
        get { return GetProperty<ParseUser>(); }
        set 
        { 
            SetProperty(value);
            // SentBy更新时通知UI同步更新手机号
            RaisePropertyChanged(nameof(SentByPhoneNumber));
        }
    }

    // 标记该字段不需要同步到Parse服务端
    [Ignore]
    public string SentByPhoneNumber
    {
        get
        {
            // 空值、字段不存在时返回空字符串避免报错
            if (SentBy == null || !SentBy.ContainsKey("phoneNumber"))
            {
                return string.Empty;
            }
            return SentBy.Get<string>("phoneNumber");
        }
    }
}

步骤2:查询时添加关联对象预加载逻辑

查询Stuff_ParseBeacon时必须显式指定需要拉取的关联字段,才能把ParseUser的手机号字段同步到本地:

var beaconQuery = ParseObject.GetQuery<Stuff_ParseBeacon>();
// 核心:预加载sentBy关联对象的所有字段
beaconQuery.Include("sentBy");
var beaconList = await beaconQuery.FindAsync();

如果是已经查询到本地的Stuff_ParseBeacon实例,也可以手动拉取关联用户的完整数据:

if (targetBeacon.SentBy != null && !targetBeacon.SentBy.IsDataAvailable)
{
    await targetBeacon.SentBy.FetchAsync();
    // 拉取完成后通知UI更新手机号
    targetBeacon.RaisePropertyChanged(nameof(targetBeacon.SentByPhoneNumber));
}

内容的提问来源于stack exchange,提问作者Le Mot Juiced

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:45:00