Otis wrote:
User001 wrote:
Otis wrote:
No I mean the C# code that creates this query.
Oh I see. Sorry, here is the code working on
IPredicate switchCondition = new PredicateExpression(OrderEntity.Fields[“Active”].IsNotNull());
IExpression switchExpre = Functions.IIF(switchCondition, 1, 0);
IEntityField2 switchField = new EntityField2("SwitchField", switchExpre);
IPredicate subQueryCondition = new PredicateExpression(CustomerEntity.Fields[“CustomerId”].Equal(1))
ScalarQueryExpression sumSwitchSe = new ScalarQueryExpression(switchField.SetAggregateFunction(AggregateFunction.Sum), subQueryCondition);
IEntityField2 sumSwitchScalarField = new EntityField2("ScalarSumSwitch", sumSwitchSe);
ResultsetFields resultsetFields = new ResultsetFields(2);
resultsetFields.Add(sumSwitchScalarField);
QueryFactory queryFactory = new QueryFactory();
DynamicQuery dynamicQuery = queryFactory.Create();
dynamicQuery.Limit(1);
dynamicQuery.Select(resultsetFields.ToArray<IEntityFieldCore>());
dynamicQuery.GroupBy(CustomerEntity.Fields[“CustomerId”]);
// Call DataAccessAdapter to fetch with dynamicQuery
(You really should use queryspec or similar to formulate queries, as it's way less verbose).
To fix it, all you have to do is replace
IEntityField2 sumSwitchScalarField = new EntityField2("ScalarSumSwitch", sumSwitchSe);
with
IEntityField2 sumSwitchScalarField = OrderFields.Active.SetExpression(sumSwitchSe);
It doesn't matter what field you pick from Order, the field itself isn't used, it's been replaced by the expression, however it IS used to determine what the target is for the scalar query
Also, please use e.g. CustomerFields.CustomerId, instead of CustomerEntity.Fields[“CustomerId”] as the latter creates a Fields object too while the former creates a just a lightweight field
Thank you for the response. I was practicing how to use ScalarQueryExpression 😅. I have tried the recommendation provided, where using the field that belongs to the OrderEntity then set the ScalarQueryExpression, so it can know which Entity to select from. However, the FROM still not showing up and still not using the subquery FROM. Here is the code generated with a beautifier.
SELECT
TOP(@p7) (
SELECT
SUM(
CASE WHEN CASE WHEN (
[Order].[Active] IS NOT NULL
) THEN 1 ELSE 0 END = 1 THEN @p2 ELSE @p4 END
) AS [SwitchField]
WHERE
(
[Customer].[CustomerId] = @p5
)
) AS [ScalarSumSwitch]
FROM
[Order]
GROUP BY
[Customer].[CustomerId] ',N' @p2 int,
@p4 int,
@p5 int,
@p7 bigint ',@p2=1,@p4=0,@p5=1,@p7=1