0

What is the problem with below code; it shows me error like illegal assignment from Account to id

Account accc=[Select Id From Account where Name='Demo Account'];
List<Contact> con=new List<Contact>();

Contact con1=new Contact(
            FirstName='Demo',LastName='Contact1',AccountId=accc
);

Contact con2=new Contact(
            FirstName='Demo',LastName='Contact2',AccountId=accc
);

con.add(con1);
con.add(con2);

Database.SaveResult[] sr=database.insert(con, false);

for(Database.SaveResult var: sr);
{
    System.debug('Result- ' + var.isSuccess());
}
1
  • 1
    You need to assign the Id of the Account like accc.Id instead of assigning the accc object
    – jagmohan
    Jun 30 at 7:32

1 Answer 1

2

Here is the updated code with comments for fixes. The primary fix is to ensure that you assign the ID of the Account as the AccountId, rather than attempting to assign the Account record itself (which is not an ID but rather a record containing an ID).

Account accc=[Select Id From Account where Name='Demo Account'];
List<Contact> con=new List<Contact>();

// assign the Id from accc object
Contact con1=new Contact(
    FirstName='Demo',LastName='Contact1',AccountId=accc.Id
);

// assign the Id from accc object
Contact con2=new Contact(
    FirstName='Demo',LastName='Contact2',AccountId=accc.Id
);

con.add(con1);
con.add(con2);

Database.SaveResult[] sr=database.insert(con, false);

// removed ; after the for statement
for(Database.SaveResult var: sr)
{
    System.debug('Result- ' + var.isSuccess());
}
2
  • Thanks @jagmohan Jun 30 at 7:41
  • You're welcome @ArunVignesh
    – jagmohan
    Jun 30 at 7:46

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.