【问题标题】:Slow LINQ query because of Where+ToDictionary由于 Where+ToDictionary 导致 LINQ 查询缓慢
【发布时间】:2021-05-07 08:46:00
【问题描述】:

我有这个查询需要运行:

IEnumerable<MerchantWithParameters> merchants =
    from i in (
        from m in d.GetTable<Merchant>()
        join mtp in d.GetTable<MerchantToParameters>() on m.Id equals mtp.MerchantId into mtps
        from mtp in mtps.DefaultIfEmpty()
        join cp in d.GetTable<ContextParameters>() on mtp.ContextParametersId equals cp.Id into cps
        from cp in cps.DefaultIfEmpty()
        select new {Merchant = m, ContextParameter = cp}
    )
    group i by new { i.Merchant.Id } into ig
    select new MerchantWithParameters()
    {
        Id = ig.Key.Id,
        Parameters = ig.Where(g => g.ContextParameter != null).ToDictionary(g => g.ContextParameter.Key, g => g.ContextParameter.Text)
    };

由于某种原因,完成此查询需要很长时间。

我认为这与它有关

Parameters = ig.Where(g => g.ContextParameter != null).ToDictionary(g => g.ContextParameter.Key, g => g.ContextParameter.Text)

因为当我删除这一行时,查询开始执行得非常快。

你能告诉我我做错了什么吗?

更新: 我正在使用 ToList() 从数据库中提取数据。

【问题讨论】:

  • 你是如何使用merchants的?
  • @Llama:我有商家,并且我在单独的表格中有参数。然后我需要将它们合并在一起:我需要具有属性作为字典的参数的商人。
  • IEnumerable&lt;MerchantWithParameters&gt; merchants = ....; 不执行查询,它只是将执行查询所需的信息存储在merchants 中。也许您以这样一种方式使用它,它会多次访问数据库来执行相同的查询?
  • @Llama:你是对的!我正在使用 ToList()

标签: c# linq linq2db


【解决方案1】:

这是已知的 SQL 限制。您无法获得分组项目,只能分组键或聚合结果。由于您需要所有记录,我们可以在客户端进行分组,但之前最大限度地限制了检索到的数据。

var query = 
    from m in d.GetTable<Merchant>()
    from mtp in d.GetTable<MerchantToParameters>().LeftJoin(mtp => m.Id == mtp.MerchantId)
    from cp in d.GetTable<ContextParameters>().LeftJoin(cp => mtp.ContextParametersId == cp.Id)
    select new 
    { 
        MerchantId = m.Id, 
        ContextParameterKey = (int?)cp.Key, 
        ContextParameterText = cp.Text
    };

var result = 
    from q in query.AsEnumerable()
    group q by q.MerchantId into g
    select new MerchantWithParameters
    {
        Id = g.Key,
        Parameters = g.Where(g => g.ContextParameterKey != null)
           .ToDictionary(g => g.ContextParameterKey.Value, g => g.ContextParameterText)
    };

var merchants = result.ToList();

【讨论】:

    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 2019-01-27
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多