[SalesForce] Illegal assignment from List to List

I have the following code sample:

@AuraEnabled
public static string getDunsByRecordId(id currentRecordID) {
    String q = 'SELECT DunsNumber FROM Account  where Id=:currentRecordID limit 1';
    List<String> dunsNumbers= Database.query(q);
    return dunsNumbers[0];
}

I want to receive the DUNS number of the record that I'm currently on, and retrieve it to the component.

The thing is, from what I understand, a query always return a list as a result, not a string.

When I write the line List<String> dunsNumbers= Database.query(q);, there is an error:

Illegal assignment from List to List

  1. How do i make it work? How do I receive one string as a duns number?
  2. Is there a way to receive a string, and not a list, as a result of a query?

Best Answer

Your query returns list of accounts. You cannot assign it to a list of String. Whenever you need field value from any object you need SOQL. Try the below code.

@AuraEnabled
public static string getDunsByRecordId(id currentRecordID) {
    List<Account> accounts = [SELECT Id, DunsNumber 
                              FROM Account  
                              WHERE Id = :currentRecordID 
                              LIMIT 1];
    return (!accounts.isEmpty()) ? accounts[0].DunsNumber : '';
}