【问题标题】:What's the best way to not join on everything exponentially?不以指数方式加入所有事情的最佳方法是什么?
【发布时间】:2021-01-27 20:29:04
【问题描述】:

我在 Linq To SQL、.Net Core 3.1.1 中有这个查询。

我想先过滤客户,然后然后对组和角色进行连接,这很不言自明,这可能会占用大量资源:

await (from customer in _dbContext.Customers
    let groupIds = _dbContext.Groups.Where(x => x.CustomerId == customer.Id).Select(x => x.Id)
    let roleIds = _dbContext.Roles.Where(x => x.CustomerId == customer.Id).Select(x => x.Id)

    where customer.Id == customerId
    select new ResultViewModel
    {
        GroupIds = groupIds.ToList(),
        RoleIds = roleIds.ToList(),
    }).FirstOrDefaultAsync();

当我查看控制台时,我看到它被翻译成这个 SQL 查询:

  SELECT [t].[Id], [g].[Id], [r].[Id], 
  FROM (
      SELECT TOP(1) [c].[Id]
      FROM [Customer] AS [c]
      WHERE [c].[Id] = @__customerId_0
  ) AS [t]
  LEFT JOIN [Group] AS [g] ON [t].[Id] = [g].[CustomerId]
  LEFT JOIN [Role] AS [r] ON [t].[Id] = [r].[CustomerId]

  ORDER BY [t].[Id], [g].[Id], [r].[Id],

此查询使我的数据库爆炸式增长。当我在 Azure Data Studio 中运行它时,我发现连接以指数方式复杂化了结果数据,因为我得到了组和角色的所有可能组合。机器上的过滤有助于减少结果,并在最后应用。 Azure Data Studio 的状态栏显示有 数百万 行涉及,即使它应该只有几

这甚至不是真正的查询。在实际中,我不仅加入了角色和组,还加入了其他 8 个字段。

作为一个测试,我已经运行了它并且它立即运行:

var customer = _dbContext.Customers.Where(c => c.Id == customerId);
var groupIds = _dbContext.Groups.Where(r => r.CustomerId == customerId).Select(x => x.Id);
var roleIds = _dbContext.Roles.Where(r => r.CustomerId == customerId).Select(x => x.Id);

return new ResultViewModel
{
    GroupIds = groupIds.ToList(),
    RoleIds = roleIds.ToList(),
};

但这并不是一个真正可接受的解决方案,因为它是 3 个查询(即来自我的后端的 3 个数据库连接)而不是一个。

我猜这只是我错误地编写了原始的 Ling To Sql 查询的问题。我做错了什么?如何避免那些不必要的连接?

【问题讨论】:

    标签: linq .net-core linq-to-sql


    【解决方案1】:

    没有客户端后期处理就没有快速解决方案。所以,建议只是快速的。

    class ConcatSet
    {
       public int? GroupId;
       public int? RoleId;
    }
    
    var groupIds = _dbContext.Groups.Where(r => r.CustomerId == customerId)
      .Select(x => new ConcatSet { GroupId = x.Id } );
    
    var roleIds  = _dbContext.Roles.Where(r => r.CustomerId == customerId)
      .Select(x => new ConcatSet { RoleId = x.Id } );
    
    var rawData = groupIds.Concat(roleIds).ToList();
    
    // for sure the following lists can be generated more effective by just enumerating rawdData
    return new ResultViewModel
    {
        GroupIds = rawData.Where(r => r.GroupId != null).Select(r => r.GroupId.Value).ToList(),
        RoleIds  = rawData.Where(r => r.RoleId != null).Select(r => r.RoleId.Value).ToList(),
    };
    

    您有一次到数据库的往返,它应该是最快的变体。

    【讨论】:

    • 是的,我自己的调查表明,目前 .Net 核心不知道如何在一个查询中填充额外的字段(无论如何它都会在后台分离数据库查询),手册具有单独变量的解决方案就足够了。谢谢!
    • 注意:显然,对于高级、优化的解决方案,人们使用名为 Dapper 的第三方库。 .Net Core 5 也可能会有所改进。
    • 我没有使用 Dapper,但更喜欢 linq2db - 比 EF 和 Dapper 快
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多