我有一个当前格式为
的Select语句dbEntity
.GroupBy(x => x.date)
.Select(groupedDate => new {
Calculation1 = doCalculation1 ? x.Sum(groupedDate.Column1) : 0),
Calculation2 = doCalculation2 ? x.Count(groupedDate) : 0)
在查询中,doCalculation1和doCalculation2是先前设置的bool。这将在生成的Sql中创建一个case语句,如
DECLARE @p1 int = 1
DECLARE @p2 int = 0
DECLARE @p3 int = 1
DECLARE @p4 int = 0
SELECT (Case When @p1 = 1 THEN Sum(dbEntity.Column1)
Else @p2
End) as Calculation1,
(Case When @p3 = 1 THEN Count(*)
Else @p4
End) as Calculation2
我想要发生的是当doCalculation1为真时生成的sql就是这样的
SELECT SUM(Column1) as Calculation1, Count(*) as Calculation2
并且当doCalculation2为假时
SELECT 0 as Calculation1, Count(*) as Calculation2
有没有办法通过EF强制查询这样做?
编辑:
bool doCalculation = true;
bool doCalculation2 = false;
dbEntity
.Where(x => x.FundType == "E")
.GroupBy(x => x.ReportDate)
.Select(dateGroup => new
{
ReportDate = dateGroup.Key,
CountInFlows = doCalculation2 ? dateGroup.Count(x => x.Flow > 0) : 0,
NetAssetEnd = doCalculation ? dateGroup.Sum(x => x.AssetsEnd) : 0
})
.ToList();
生成此sql
-- Region Parameters
DECLARE @p0 VarChar(1000) = 'E'
DECLARE @p1 Int = 0
DECLARE @p2 Decimal(5,4) = 0
DECLARE @p3 Int = 0
DECLARE @p4 Int = 1
DECLARE @p5 Decimal(1,0) = 0
-- EndRegion
SELECT [t1].[ReportDate],
(CASE
WHEN @p1 = 1 THEN (
SELECT COUNT(*)
FROM [dbEntity] AS [t2]
WHERE ([t2].[Flow] > @p2) AND ([t1].[ReportDate] = [t2].[ReportDate]) AND ([t2].[FundType] = @p0)
)
ELSE @p3
END) AS [CountInFlows],
(CASE
WHEN @p4 = 1 THEN CONVERT(Decimal(33,4),[t1].[value])
ELSE CONVERT(Decimal(33,4),@p5)
END) AS [NetAssetEnd]
FROM (
SELECT SUM([t0].[AssetsEnd]) AS [value], [t0].[ReportDate]
FROM [dbEntity] AS [t0]
WHERE [t0].[FundType] = @p0
GROUP BY [t0].[ReportDate]
) AS [t1]
在执行计划中有许多索引扫描和一个假脱机和一个连接。在测试装置上平均运行大约需要20秒,生产设置会更大。
我希望它以与sql相同的速度运行,如
select reportdate, 1, sum(AssetsEnd)
from vwDailyFundFlowDetail
where fundtype = 'E'
group by reportdate
平均运行大约12秒,并且大部分查询都绑定在执行计划中的单个索引中。实际的sql输出并不重要,但是case语句的性能似乎要差得多。
至于为什么我这样做,我需要像Dynamically generate Linq Select中那样生成一个动态的select语句。用户可以选择要执行的一组计算中的一个或多个,并且在请求进入之前我将不知道所选择的内容。请求是昂贵的,因此我们不希望运行它们,除非它们是必要的。我根据用户请求设置了doCalculation bools。
此查询应该替换一些代码,这些代码插入或删除存储为字符串的硬编码sql查询中的字符,然后执行该代码。这运行得相当快,但维持是一场噩梦
答案 0 :(得分:2)
技术上可以通过an expression tree visitor在Select查询中传递Expression,它在三元运算符的左侧检查常量值,并用适当的子表达式替换三元表达式。
例如:
public class Simplifier : ExpressionVisitor
{
public static Expression<T> Simplify<T>(Expression<T> expr)
{
return (Expression<T>) new Simplifier().Visit(expr);
}
protected override Expression VisitConditional(ConditionalExpression node)
{
var test = Visit(node.Test);
var ifTrue = Visit(node.IfTrue);
var ifFalse = Visit(node.IfFalse);
var testConst = test as ConstantExpression;
if(testConst != null)
{
var value = (bool) testConst.Value;
return value ? ifTrue : ifFalse;
}
return Expression.Condition(test, ifTrue, ifFalse);
}
protected override Expression VisitMember(MemberExpression node)
{
// Closed-over variables are represented as field accesses to fields on a constant object.
var field = (node.Member as FieldInfo);
var closure = (node.Expression as ConstantExpression);
if(closure != null)
{
var value = field.GetValue(closure.Value);
return VisitConstant(Expression.Constant(value));
}
return base.VisitMember(node);
}
}
用法示例:
void Main()
{
var b = true;
Expression<Func<int, object>> expr = i => b ? i.ToString() : "N/A";
Console.WriteLine(expr.ToString()); // i => IIF(value(UserQuery+<>c__DisplayClass0).b, i.ToString(), "N/A")
Console.WriteLine(Simplifier.Simplify(expr).ToString()); // i => i.ToString()
b = false;
Console.WriteLine(Simplifier.Simplify(expr).ToString()); // i => "N/A"
}
所以,你可以在你的代码中使用这个:
Expression<Func<IGrouping<DateTime, MyEntity>>, ClassYouWantToReturn> select =
groupedDate => new {
Calculation1 = doCalculation1 ? x.Sum(groupedDate.Column1) : 0),
Calculation2 = doCalculation2 ? x.Count(groupedDate) : 0
};
var q = dbEntity
.GroupBy(x => x.date)
.Select(Simplifier.Simplify(select))
然而,这可能比它的价值更麻烦。 SQL Server几乎无疑会优化&#34; 1 == 1&#34;案例之外,允许实体框架生成不太漂亮的查询不应该被证明是一个性能问题。
查看更新后的问题,这似乎是生成正确查询确实无关紧要的少数几个实例之一。
除了我建议的解决方案之外,还有其他一些选择:您可以use raw sql映射到您的返回类型,或者您可以使用LinqKit根据您的需要选择不同的表达式,以及然后&#34;调用&#34; Select表达式中的表达式。