3

I have a soql on a custom object this returns 2 rows in the Anonymous window and in the Query editor. If I use the same query in an apex class it returns empty. I is there something I am missing.

query in Anonymouse / Query editor

SELECT id, Kontakt2__c FROM Anfrage__c

enter image description here

enter image description here

query in apex class

public class NavigateToAnfrageDetailPage {
    @AuraEnabled
    public static String getLoggedInUser(){
        User currentUser = [SELECT id, ContactId FROM User WHERE id =: UserInfo.getUserId() LIMIT 1];
        string cU = currentUser.ContactId;     

        List<Anfrage__c> anfrage = [SELECT id, Kontakt2__c  FROM Anfrage__c];
        system.debug('anfrage '+ anfrage);

       if(anfrage.size() > 0){
           return anfrage[0].id;
                           }else{
                               return NULL;
                   }
    }
}

Log

18:20:01.0 (15419698)|SOQL_EXECUTE_BEGIN|[14]|Aggregations:0|SELECT id, Kontakt2__c FROM Anfrage__c
18:20:01.0 (25200714)|SOQL_EXECUTE_END|[14]|Rows:0

  • 2
    Always declare sharing in your class definition. – Adrian Larson Mar 12 '18 at 17:27
  • What are the sharing settings on this object? Do you actually have read access to the records you got back in the Query Editor? – Adrian Larson Mar 12 '18 at 17:34
  • This would be due to record access differences in context of querying over api vs apex. As Adrian mentioned, by adding "with sharing" to apex class, you will ensure only shared records are queried. – realfire Mar 12 '18 at 17:34
3

As Adrian and datasert posted in comments, your problem is very likely sharing.

In most cases, when you do not specify sharing in a class, without sharing is implied (see here), which wouldn't cause the error you are seeing.

Here is the relevant excerpt (emphasis is mine)

If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that the class doesn’t enforce sharing rules except if it acquires sharing rules from another class. For example, if the class is called by another class that has sharing enforced, then sharing is enforced for the called class.

However, if you have not activated this Critical Update, this behavior is different, and sharing is being applied.

Relevant excerpt:

Previously, Lightning component controllers that didn’t explicitly set a sharing behavior operated as though with sharing was set. This behavior is the opposite of Apex operating in other contexts, such as Visualforce controllers.

As you can read in both documents, however, best practice is to always specify one type of sharing.

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.