function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ertyq MrskErtyq Mrsk 

AuraEnabled Apex Class Returning Following Error: System.QueryException: List has no rows for assignment to SObject

In my following AuraEnabled class, I am trying to clone the current record displayed in my lightning component page. This lightning component implements force:hasRecordId and should insert it as new value instead of updating the current one.

But upon checking the developer console's debug logs, I always see this error:

System.QueryException: List has no rows for assignment to SObject

What should I do to fix said error?

ItemsController.cls
public with sharing class ItemsController {
    
    @AuraEnabled
    public static Item__c cloneItem(Id itemId){
        
        Item__c itemToClone = new Item__c();

        itemToClone = [SELECT Id, MasterField__c FROM Item__c WHERE Id =: itemId LIMIT 1];

        Item__c newCloneItem = new Item__c();
        newCloneItem = itemToClone.clone();
        newCloneItem.MasterField__c = itemToClone.MasterField__c;
        insert newCloneItem; 
       
        return newCloneItem;
    }
   
}

 
RituSharmaRituSharma
Put a debug statement in APEX to see if itemId is getting value from lightning. If not, debug lightning component to see why it's not passing the value to the apex.
AbhishekAbhishek (Salesforce Developers) 
The exception is because you are not getting any record in your SOQL query which meets the where criteria so it gives an error. When attempting to fetch a single record from the database it is easy to run into the above exception. To avoid such exception use a try-catch box like below :

MyObject__c obj;

try{

obj = [SELECT id FROM MyObject__c WHERE name=:previouslyDefinedVar];

} catch(System.QueryException e){

// Perform logic here

}

For further reference, you can check this too,

https://stackoverflow.com/questions/48645338/list-has-no-rows-for-assignment-to-sobject-error-although-query-returns-rows


Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks.