英文:
How to expand the projection in SELECT if a condition is met?
问题
我需要从查询结果中选择(执行投影),只选择一组基本列。因此,我有一个定义的表达式,列出了所有所需的属性:
Expression<Func<Input, Output>> basicExpression = x => new Output
{
OutputProp1 = x.TABLE1.TABLE2.InputProp1
}
我可以在Select
语句中使用这个变量:
dbContext.Input.Select(basicExpression)
如果系统中的特定标志设置为true,我应该投影一个名为OutputProp2的额外字段
是否有一种方式可以将成员初始化表达式注入到原始的Select
表达式中?
Expression<Func<Input, Output>> basicExpression = x => new Output
{
OutputProp1 = x.TABLE1.TABLE2.InputProp1,
OutputProp2 // <------ 如果标志设置为true,则在此处插入此属性
}
我不能简单地替换对basicExpression
的引用,因为查询将根据系统中启用/禁用的标志的组合而变化。
英文:
I need to select (do a projection) only basic set of columns from the query result. Therefore I have an expression defined, listing all of the required properties:
Expression<Func<Input, Output>> basicExpression = x => new Output
{
OutputProp1 = x.TABLE1.TABLE2.InputProp1
}
I can use this variable in a Select
statement:
dbContext.Input.Select(basicExpression)
If a specific flag in the system is set to true, I should project one more field called OutputProp2
Is there a way of how could I inject the Member init expression into the original Select
expression?
Expression<Func<Input, Output>> basicExpression = x => new Output
{
OutputProp1 = x.TABLE1.TABLE2.InputProp1,
OutputProp2 <------ insert this prop here if a flag is set to true
}
I cannot simply replace the reference to basicExpression
because the query will vary depending on a combination of flags enabled/disabled in the system.
答案1
得分: 1
Output.OutputProp存在于条件为True或False时,因此基于条件是否合理“添加”它到表达式或不添加,而是基于条件设置它:
Expression<Func<Input, Output>> basicExpression = x => new Output
{
OutputProp1 = x.TABLE1.TABLE2.InputProp1,
OutputProp2 = flag ? x.TABLE1.TABLE2.SomeProp / Calc : default;
}
现在,你是否能确保EF仍然可以将整个表达式翻译成SQL是另一个问题。
英文:
Output.OutputProp exists whether your condition is True or False so it doesn't make sense to "add" it to the expression or not based on a condition, rather set it based on the condition:
Expression<Func<Input, Output>> basicExpression = x => new Output
{
OutputProp1 = x.TABLE1.TABLE2.InputProp1,
OutputProp2 = flag ? x.TABLE1.TABLE2.SomeProp/Calc : default;
}
Now whether you can ensure EF can still translate the entire expression down to SQL is another can of worms.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论