1

Why am getting the following error

Illegal assignment from List<AggregateResult> to List<BOG_Membership__c>

for this code? And what to do?

    List<BOG_Membership__c> aggregates = [
    SELECT Contact__r.AccountId , Contact__r.FirstName , Contact__r.LastName 
        FROM BOG_Membership__c 
        WHERE Contact__r.AccountId = '0012000000fyND0'
        GROUP BY Contact__r.AccountId, Contact__r.FirstName, Contact__r.LastName    
];
1

Aggregate queries always return a:

List<AggregateResult>

so your code needs to be:

List<AggregateResult> aggregates = [...];

(Adding the GROUP BY turns the query into an aggregate query.)

See e.g. Working with SOQL Aggregate Functions for examples of how to get the result values from the AggregateResult object.

| improve this answer | |
1

Since you have a GROUP BY clause in your query, salesforce is returning a list type of AggregateResult. So you have to have something like

List<AggregateResult> aggregates = [
    SELECT Contact__r.AccountId , Contact__r.FirstName , Contact__r.LastName 
        FROM BOG_Membership__c 
        WHERE Contact__r.AccountId = '0012000000fyND0'
        GROUP BY Contact__r.AccountId, Contact__r.FirstName, Contact__r.LastName    
];

I'd suggest few more things here when it comes to iterating over a list of AggregateResult. You have to use aliases for your fields which gives you the ease of access them inside the loop. If you don't and if you have more than one same fields (Id, Name, etc. in different lookup objects) then you will be in trouble.

List<AggregateResult> aggregates = [
        SELECT Contact__r.AccountId aid , Contact__r.FirstName cfName, Contact__r.LastName clName
            FROM BOG_Membership__c 
            WHERE Contact__r.AccountId = '0012000000fyND0'
            GROUP BY Contact__r.AccountId, Contact__r.FirstName, Contact__r.LastName    
    ];
for(AggregateResult ar : aggregates){
    System.debug(ar.get('aid'));
    System.debug(ar.get('cfName'));
    System.debug(ar.get('clName'));
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.