由于 Where+ToDictionary,LINQ 查询变慢

Slow LINQ query because of Where+ToDictionary

我有这个查询需要 运行:

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() 从数据库中提取数据。

已知 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();