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

.NET中使用MemoryCache存储含嵌套列表对象时Bars为空的问题排查

问题:使用MemoryCache存储包含集合属性的复杂对象时,集合属性丢失

我尝试使用Microsoft.Extensions.Caching.Memory.MemoryCache存储复杂对象,数据结构如下:

public class Foo
{
    public Guid Id { get; set; }
    public IList<Bar> Bars { get; set; }
}

public class Bar
{
   public Guid Id { get; set; }
   public Guid ParentFooId { get; set; }
}

我通过API调用获取包含Bars的Foo实例,并用以下代码存入缓存:

CacheInstance = new MemoryCache();

CacheInstance.Set(fooInstance.Id, fooInstance);

//后续操作:
var cached = CacheInstance.Get<Foo>(foo.Id);

但取出后,cached是有效的Foo对象,但其Bars属性为空。请问如何存储并获取保留Bars的Foo对象?


已解决

借助提示和示例,我定位了问题:应用中存在另一个类Zee,结构如下:

public class Zee
{
    public Guid Id { get; set; }
    public IList<Guid> FooIds { get; set; }
}

当缓存Zee实例时,程序会遍历其FooIds并从API获取对应的Foo,但调用的这个接口不会返回Bars,导致缓存中已有的完整Foo被这些不完整的版本覆盖。由于操作是异步执行的,很难定位覆盖来源。感谢大家澄清MemoryCache机制并指明方向!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:54:24