System.QueryException: invalid ID field: null

To avoid "System.QueryException: invalid ID field: null", before adding to a list or set, check whether you are adding null.

For example, check the below code

set<Id> acctIds = new set<Id>();
for(Contact con : contactList) {
    acctIds.add(con.AccountId);
}

List<Account> listAccount = [SELECT Id, Name FROM Account WHERE ID IN: acctIds];

Account is not a required field in Contact. So, there is a chance for this field to be blank. You can rewrite the logic as below

Code to avoid null in SOQL:

set<Id> acctIds = new set<Id>();
for(Contact con : contactList) {
    if(con.AccountId != null) {
        acctIds.add(con.AccountId);
    }
}

List<Account> listAccount = [SELECT Id, Name FROM Account WHERE ID IN: acctIds];

Account is not a required field in Contact. So, there is a chance for this field to be blank. So, before adding it to the set, I have checked whether it is null.

Cheers!!!

No comments:

Post a Comment