【发布时间】:2020-03-24 22:59:18
【问题描述】:
我的模型在 2 个或多个属性中是独一无二的。例如,Entity 类的对象在名称和 ID 上都是唯一的。
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
}
我有一个模型存储库:
public class EntityRepository
{
...
public Entity GetById(int id)
{
return db.GetById(id);
}
public Entity GetByName(string name)
{
return db.GetByName(name);
}
}
缓存对GetById 的调用和使用Microsoft.Extensions.Caching.Memory.IMemoryCache 对GetByName 的调用的最佳方法是什么?
目前的解决方案:
public class EntityRepository
{
...
public Entity GetById(int id)
{
return Cache.GetOrCreate($"id:{id}", cacheEntry =>
{
return db.GetById(id);
});
}
public Entity GetByName(string name)
{
return Cache.GetOrCreate($"name:{name}", cacheEntry =>
{
return db.GetByName(name);
});
}
public void RemoveById(int id)
{
db.RemoveById(id);
Cache.Remove($"id:{id}");
}
}
这里的问题是,如果我通过它的 ID 删除一个实体,我可以通过 ID 从缓存中删除它,但它仍然会与另一个键一起存在。更新实体也有类似的问题。
有没有比将对象两次保存在缓存中更好的解决方案?
【问题讨论】:
标签: c# asp.net-core caching .net-core memorycache