使用 Linq to Entities 在单个查询中选择多个属性。我在 lambda 表达式中有 if then else 条件来选择这样的属性:
Repository.Select(
x => Condition1 ? x.Property1 : x.Property2,
y => Condition2 ? y.Property1 : y.Property2,
z => .....);
生成的 sql 不必要地复杂。我想让它不包括开始的 if else 条件。有没有办法让它评估条件,即只是
x=> x.Property1
在生成 sql 之前?
最佳答案
您想评估条件和服务器端对吗?
一种可能的方法是编写辅助方法:
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
基于 condition
将单个属性选择器作为表达式返回。选择选择器是在服务器端完成的,因此您的 sql 应该得到简化。
关于c# - Linq to entities if else 条件查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32991486/