【问题标题】:Is LINQ querying the database, making my caching useless?LINQ 是否正在查询数据库,使我的缓存无用?
【发布时间】:2022-01-11 07:53:53
【问题描述】:

所以我有一些这样的代码:

var attribute = _genericAttributeService
    .GetAttributesForEntity(_workContext.CurrentCustomer.Id, "Customer")
    .FirstOrDefault(x => x.Key == "CompareProducts");

GetAttributesForEntity 看起来像这样:

public virtual IList<GenericAttribute> GetAttributesForEntity(int entityId, string keyGroup)
{
    return _cacheManager.Get(string.Format(GENERICATTRIBUTE_KEY, entityId, keyGroup), () =>
    {
        var query = from ga in _genericAttributeRepository.Table
                            where ga.EntityId == entityId &&
                            ga.KeyGroup == keyGroup
                            select ga;
        var attributes = query.ToList();
        return attributes;
    });
}

所以它使用缓存来减少数据库查询。

FirstOrDefault() 现在是在查询返回的列表,还是进行了另一个数据库查询? 很高兴知道这里发生了什么。

【问题讨论】:

  • 如果我们不知道 _cacheManager 是什么,我们就无法知道。您可以随时profile the database 了解正在发生的事情。
  • @Crowcoder 说了什么。请添加 CacheManager 的代码或至少一个包的链接。
  • @Crowcoder cachemanager 按请求缓存
  • 一个缓存在另一个缓存前面通常是没用的。有时甚至适得其反。
  • 虽然您可能正在缓存实体的所有属性,但我会缓存一个字典并更改 API 以查询该字典。扫描整个列表以查找一个项目感觉有点贵。

标签: c# mysql performance linq nopcommerce


【解决方案1】:

现在是 FirstOrDefault() 查询返回的列表,还是另一个 进行了数据库查询?

简答:

FirstOrDefault 将查询缓存列表。

长答案:

_cacheManager 将使用提供的参数(entityId, keyGroup) 从缓存中检索列表。

如果元素不在缓存中,它将执行 lambda 从数据库中检索数据,并将结果与​​键 (entityId, keyGroup) 一起存储。

它将存储完整的List&lt;&gt;。注意语句:

var attributes = query.ToList();

因此,如果您使用相同的参数重复调用GetAttributesForEntity,您将获得存储的结果。

注意:NopCommerce 实现了不同的缓存级别,以及缓存失效程序,我暂时不深入探讨。

【讨论】:

  • 嗨,Marco,感谢您的确认,我不确定 :) 我意识到这些查询无论如何都可以改进,我将继续努力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 2011-03-21
  • 2015-04-09
相关资源
最近更新 更多