Trying to make this work but receiving "Relation at index 1 doesn't contain an entity already added to the FROM clause. Bad alias?", must be doing something wrong here, could you have a look at the following:
RelationPredicateBucket bucket = new RelationPredicateBucket();
// first specify the elements in the derived table select (which is a dyn. list)
ResultsetFields dtFields = new ResultsetFields(2);
dtFields.DefineField(ProjectCellsFields.ProjectId, 0);
dtFields.DefineField(new EntityField2("NumberOfCells",
(ProjectCellsFields.CellId * 1), AggregateFunction.Count), 1);
GroupByCollection dtGroupBy = new GroupByCollection(dtFields[0]);
DerivedTableDefinition dtDefinition = new DerivedTableDefinition(dtFields, "ProjectCellsCounters", null, dtGroupBy);
// then specify the relation.
// derivedtable spec, join type, end entity type, alias first element, alias end element, on clause filter
DynamicRelation relation = new DynamicRelation(dtDefinition, JoinHint.Inner,
EntityType.ProjectsEntity, "P",
(new EntityField2(ProjectCellsFieldIndex.ProjectId.ToString(), "ProjectCellsCounters", typeof(int)) ==
ProjectsFields.ProjectId.SetObjectAlias("P")));
// then specify the rest of the query elements
bucket.Relations.Add(relation);
bucket.SelectListAlias = "P";
Thanks!