0

I am doing a wrapper class binding account and its related contact and opp record.

For starters, there is only one Account with the name 'Account1'. 'Account1' only has 1 Contact and 1 Opportunity.

My code is as follows:

public class Example1 {

 
public Example1(){
    
    WrapperClass WC1 = new WrapperClass();
    wc1.acc=[Select ID, Name from Account Where Name ='Account1'];
    wc1.con=[Select ID, Name from Contact Where ID = :wc1.acc.id];
    wc1.opty=[Select ID, Name from Opportunity Where ID = :wc1.acc.id];
    system.debug(wc1);
}


Public Class WrapperClass{
    public Account acc;
    public Contact con;
    public Opportunity opty; 
      
} }

I am getting the following error

Line: 8, Column: 1
System.QueryException: List has no rows for assignment to SObject

Please advise.

2

There's two errors here. In both you Contact and Opportunity query you're WHERE clause is incorrect. You're comparing the Contact and Opportunity Ids respectively to the Account Id, which is incorrect. For bother queries, you want WHERE AccountId = :wc1.acc.Id.

0

I have checked your code and I found that there is a problem with your code.

The error has occurred because you're trying to match the ContactId/OpportunityId with the AccountId - in the WHERE clause you are using Id =: wc1.acc.id whereas you have to use WHERE AccountID =: wc1.acc.id where you're fetching both the Contact and Opportunity.

Here is your code with modifications:-

public class Example1 {  
    
    public Example1(){
        
        WrapperClass WC1 = new WrapperClass();
        wc1.acc=[Select ID, Name from Account Where Name ='Account1'];
        List<Contact> cont = [Select ID from Contact Where AccountID = :wc1.acc.id];
        if(cont.size()>0){
            wc1.con=[Select ID, Name from Contact Where AccountID = :wc1.acc.id limit 1];
        }
        List<Opportunity> opp = [Select ID from Opportunity Where AccountID = :wc1.acc.id];
        if(opp.size()>0){
            wc1.opty=[Select ID, Name from Opportunity Where AccountID = :wc1.acc.id limit 1];
        }
        system.debug(wc1);
    }
    
    Public Class WrapperClass{
        public Account acc;
        public Contact con;
        public Opportunity opty;
        
    } 
}

Hope this explanation will resolve your query.

Thanks

Akshay

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.