【发布时间】: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