Frans (aka Otis) -
I decided to post here rather than have Jim continue with this through your helpdesk, since we thought it was different and really isn't.
Otis wrote:
THis thread is continued in the helpdesk forum.
Btw, you can write the query as:
SELECT *
FROM Account
WHERE AccountID
IN
(
SELECT AccountID
FROM Score
WHERE ScoreID =
(
SELECT TOP 1 ScoreID FROM Score s
WHERE s.AccountID = Score.AccountID
ORDER BY StartDate DESC
)
AND
Score > 1
)
Which leads to code as (from my bare head, while peeking into the ref manual (which is in the installation folder) so it might contain a small syntax error here and there)
EntityCollection<AccountEntity> accounts = new EntityCollection<AccountEntity>();
RelationPredicateBucket filter = new RelationPredicateBucket();
filter.Add(new FieldCompareSetPredicate(
AccountFields.AccountID, null, // field to compare
ScoreFields.AccountID, null, // set field (the field in the inner select)
SetOperator.In, // the IN operator
new PredicateExpression(new FieldCompareSetPredicate( // the filter which selects from score
ScoreFields.ScoreID, null,
ScoreFields.ScoreID.SetObjectAlias("s"), null,
SetOperator.Equal,
(ScoreFields.AccountID.SetObjectAlias("s")==ScoreFields.AccountID),
null,
1, // the TOP 1
new SortExpression(ScoreFields.StartDate | SortOperator.Descending)))
.AddWithAnd(ScoreFields.Score > 1))); // append the AND (score > 1) filter to the predicateex.
using(DataAccessAdapter adapter=new DataAccessAdapter())
{
adapter.FetchEntityCollection(accounts, filter);
}
The SQL query you have above does work and is much simpler.
I was able to get your from-your-head code working (I only needed to add an empty string in the FieldCompareSetPredicate .ctor just before the maxNumberOfItemsToReturn value (for the object alias)), but it would blow up unless I included the following line:
filter.Relations.Add(AccountEntity.Relations.ScoreEntityUsingAccountID);
However, this code produces the following SQL, which is not giving the same results:
SELECT DISTINCT Account.AccountID
FROM Account INNER JOIN Score
ON Account.AccountID = Score.AccountID
WHERE Account.AccountID IN
(
SELECT Score.AccountID
FROM Score
WHERE Score.ScoreID =
(
SELECT TOP 1 s.ScoreID
FROM Score AS s
WHERE s.AccountID = Score.AccountID
ORDER BY Score.StartDate DESC
)
AND Score.Score > 1
)
Considering the complexity of this, I am at a loss at what to do differently. Is the SQL being produced by your code not as you expect it? Or is it that we need to write it differently? Help is appreciated, as this one is driving me bananas at this point.
Thanks