如何在满足条件时扩展SELECT中的投影?

huangapple go评论63阅读模式
英文:

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&lt;Func&lt;Input, Output&gt;&gt; basicExpression = x =&gt; 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&lt;Func&lt;Input, Output&gt;&gt; basicExpression = x =&gt; new Output 
{
  OutputProp1 = x.TABLE1.TABLE2.InputProp1,
  OutputProp2  &lt;------ 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是另一个问题。 如何在满足条件时扩展SELECT中的投影?

英文:

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&lt;Func&lt;Input, Output&gt;&gt; basicExpression = x =&gt; 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. 如何在满足条件时扩展SELECT中的投影?

huangapple
  • 本文由 发表于 2023年6月30日 04:44:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定