Linq to entities if else 条件查询
Linq to entities if else condions in query
使用 Linq to Entities 在单个查询中 select 多个属性。我在 lambda 表达式中有 if then else 条件到 select 属性,如下所示:
Repository.Select(
x => Condition1 ? x.Property1 : x.Property2,
y => Condition2 ? y.Property1 : y.Property2,
z => .....);
生成的 sql 不必要地复杂。我想让它不包括开始的 if else 条件。有没有办法让它评估条件,即
x=> x.Property1
在生成 sql?
之前
我想这取决于条件是按数据集还是按行。如果查询返回的每一行的条件 1 为真或假,则必须将其提交给数据库进行评估。
否则,如果条件 1 为真并且可以在 运行 查询之前在 C# 中进行评估,则对于每一行都为真,在这种情况下,您可以在 C# 中进行评估并进行基于不同的投影关于结果,例如
if (Condition1 && Condition2) {
Repository.Select(x => x.Property1,
y => y.Property1
} else if (...) {
...
}
对于很多条件来说可能并不理想,但据我所知,这是一种停止发送大量条件以供数据库进行不必要评估的方法。
您想评估条件和服务器端对吗?
一种可能的方法是编写辅助方法:
public Expression<Func<TInput, TOutput>> ResolveProp<ITinput, TOutput>(
Expression<Func<TInput, TOuput>> propSelector1,
Expression<Func<TInput, TOuput>> propSelector2,
bool condition){
return condition ? propSelector1 : propSelector2;
}
用法:
Repository.Select(ResolveProp<SomeEntity, PropType>(
x => x.Property1,
x => x.Property2,
Condition1),
...)
ResolveProp
returns 单个 属性 选择器作为表达式,基于 condition
。选择选择器是在服务器端完成的,因此您的 sql 应该得到简化。
使用 Linq to Entities 在单个查询中 select 多个属性。我在 lambda 表达式中有 if then else 条件到 select 属性,如下所示:
Repository.Select(
x => Condition1 ? x.Property1 : x.Property2,
y => Condition2 ? y.Property1 : y.Property2,
z => .....);
生成的 sql 不必要地复杂。我想让它不包括开始的 if else 条件。有没有办法让它评估条件,即
x=> x.Property1
在生成 sql?
之前我想这取决于条件是按数据集还是按行。如果查询返回的每一行的条件 1 为真或假,则必须将其提交给数据库进行评估。
否则,如果条件 1 为真并且可以在 运行 查询之前在 C# 中进行评估,则对于每一行都为真,在这种情况下,您可以在 C# 中进行评估并进行基于不同的投影关于结果,例如
if (Condition1 && Condition2) {
Repository.Select(x => x.Property1,
y => y.Property1
} else if (...) {
...
}
对于很多条件来说可能并不理想,但据我所知,这是一种停止发送大量条件以供数据库进行不必要评估的方法。
您想评估条件和服务器端对吗?
一种可能的方法是编写辅助方法:
public Expression<Func<TInput, TOutput>> ResolveProp<ITinput, TOutput>(
Expression<Func<TInput, TOuput>> propSelector1,
Expression<Func<TInput, TOuput>> propSelector2,
bool condition){
return condition ? propSelector1 : propSelector2;
}
用法:
Repository.Select(ResolveProp<SomeEntity, PropType>(
x => x.Property1,
x => x.Property2,
Condition1),
...)
ResolveProp
returns 单个 属性 选择器作为表达式,基于 condition
。选择选择器是在服务器端完成的,因此您的 sql 应该得到简化。