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
AM_SFDCAM_SFDC 

Not able t ocreate new contact throught this code

I am trying to add a new contact record with below condition where Account has greter than  99 employees  an limit is 1.
Though new  contact is not getting created in accounts where  employess are more than 99.
let me know what is wrong in below code.
(New to apex)
Contact c = new Contact(Account = [SELECT Name FROM Account 
    WHERE NumberOfEmployees > 99 Limit 1]);
c.FirstName = 'Test';
c.LastName = 'AM';
System.debug('Contact name  is '+c);    
Andrew GAndrew G
Issues with your sample:
1. The "link" from Contact to Account is via the AccountId field, Account field.  
2.   SELECT query will return the Name but you need to set an Id to the AccountId field.
3. c in your code would be a contact record, so your debug would give a output of Contact, and in this case, just the Id, First & Last Names.  
4. There is no insertion or retrievel of the contact some things like "Name" will not have been calculated.

so, a sample:
Account account = [SELECT Id FROM Account 
    WHERE NumberOfEmployees > 99 Limit 1]);

if (Account != null) {
    Contact c = new Contact();
    c.AccountId = account.Id;
    c.FirstName = 'Test';
    c.LastName = 'AM';
   insert c;
}
Contact insertedContact = [SELECT Name FROM Contact WHERE Id = c.Id];
System.debug('New contact name is ' + insertedContact.Name);
I hope that this code is just something that you are playing with, as the logic of how you are selecting your Account record could lead to the same account record being selected multiple times, and hence this new "AM Test" contact could be added multiple times to the Account.


Regards
Andrew