LINQ to SQL:参数化的 keySelector 导致 LINQPad 中的本地评估
LINQ to SQL: Parameterized keySelector causes local evaluation in LINQPad
我有一个 LINQ to SQL 函数,我允许将 keySelector 函数作为参数:
Func<App, string> keySelector = a => a.Name;
Apps.GroupBy(keySelector).Select(g => new { Key = g.Key, Count = g.Count() }).Dump();
但是,当我查看生成的 SQL 时,很明显初始 table 查询之后的所有内容都在本地进行评估,更糟糕的是,它正在查询 table 的每一列table:
SELECT [t0].[AppId], [t0].[Name], [t0].[PublisherId], [t0].[PlatformId], [t0].[UnifiedAppId]
FROM [apps].[App] AS [t0]
如果我改为内联指定 keySelector 函数,它会按预期工作:
Apps.GroupBy(a => a.Name).Select(g => new { Key = g.Key, Count = g.Count() }).Dump();
SELECT COUNT(*) AS [Count], [t0].[Name] AS [Key]
FROM [apps].[App] AS [t0]
GROUP BY [t0].[Name]
我有什么想法可以让它发挥作用吗?谢谢!!
将您的 KeySelector 更改为表达式
即
Expression<Func<App, string>> keySelector = a => a.Name;
Apps.GroupBy(keySelector).Select(g => new { Key = g.Key, Count = g.Count() }).Dump();
我有一个 LINQ to SQL 函数,我允许将 keySelector 函数作为参数:
Func<App, string> keySelector = a => a.Name;
Apps.GroupBy(keySelector).Select(g => new { Key = g.Key, Count = g.Count() }).Dump();
但是,当我查看生成的 SQL 时,很明显初始 table 查询之后的所有内容都在本地进行评估,更糟糕的是,它正在查询 table 的每一列table:
SELECT [t0].[AppId], [t0].[Name], [t0].[PublisherId], [t0].[PlatformId], [t0].[UnifiedAppId]
FROM [apps].[App] AS [t0]
如果我改为内联指定 keySelector 函数,它会按预期工作:
Apps.GroupBy(a => a.Name).Select(g => new { Key = g.Key, Count = g.Count() }).Dump();
SELECT COUNT(*) AS [Count], [t0].[Name] AS [Key]
FROM [apps].[App] AS [t0]
GROUP BY [t0].[Name]
我有什么想法可以让它发挥作用吗?谢谢!!
将您的 KeySelector 更改为表达式
即
Expression<Func<App, string>> keySelector = a => a.Name;
Apps.GroupBy(keySelector).Select(g => new { Key = g.Key, Count = g.Count() }).Dump();