我想为我动态构建 - 子句的某个查询计算行数WHERE
。
让我兴奋的是我在以两种不同的方式构建它时看到的不同。
试试 1
int resultsCount = context.MyView.Where(x => x.Id > 100000).Count();
在我看到的探查器中,正在执行以下查询:
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM (SELECT
[MyView].[Id] AS [Id],
[MyView].[EventTypeId] AS [EventTypeId],
[MyView].[EventSourceId] AS [EventSourceId],
[MyView].[TraceLevelId] AS [TraceLevelId],
[MyView].[TimeCreated] AS [TimeCreated],
[MyView].[Data1MaxStr] AS [Data1MaxStr]
FROM [dbo].[MyView] AS [MyView]) AS [Extent1]
WHERE [Extent1].[Id] > 100000
) AS [GroupBy1]
试试 2
但是我必须检查多个条件,并不是每次执行都需要满足所有条件。所以我尝试WHERE
为我的COUNT
动态构建 - 子句(参考这篇文章):
var parameter = Expression.Parameter(typeof(MyView), "x");
Expression<Func<MyView, bool>> check1 = x => x.Id > 100000;
Expression expression = Expression.Constant(true);
expression = Expression.AndAlso(expression, Expression.Invoke(check1, parameter));
var lambda = Expression.Lambda<Func<MyView, bool>>(expression, parameter);
int resultsCount = context.MyView.Where(lambda.Compile()).Count();
我希望看到执行相同或至少类似的查询,但我在分析器中看到以下内容:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[EventTypeId] AS [EventTypeId],
[Extent1].[EventSourceId] AS [EventSourceId],
[Extent1].[TraceLevelId] AS [TraceLevelId],
[Extent1].[TimeCreated] AS [TimeCreated],
[Extent1].[Data1MaxStr] AS [Data1MaxStr]
FROM (SELECT
[MyView].[Id] AS [Id],
[MyView].[EventTypeId] AS [EventTypeId],
[MyView].[EventSourceId] AS [EventSourceId],
[MyView].[TraceLevelId] AS [TraceLevelId],
[MyView].[TimeCreated] AS [TimeCreated],
[MyView].[Data1MaxStr] AS [Data1MaxStr]
FROM [dbo].[MyView] AS [MyView]) AS [Extent1]
然而的值resultsCount
是相同的,但为什么这些查询如此不同,LinQ 在哪里获得COUNT
第二个查询,因为我没有看到任何COUNT
被选中?
有人可以告诉我如何强制执行类似于第一个但仍WHERE
动态构建我的 - 子句的查询吗?
任何提示将不胜感激。