+ Start a Discussion
AAMAAM 

Dynamic SOQL - Grab Account Name from Database.QueryString

I have the following QueryString:

 

String QueryString = 'SELECT Id, Name, AccountId, Account.Name, Phone, Email, OwnerId, Owner.Alias, Active__c, Broker_Number__c, Broker_Number__r.Name, Account.Firm__c FROM Contact WHERE' + QueryActive;

 

 

I need to loop through the results and populate a list:

 

for(sObject o : Database.query(QueryString))
{
	SearchContact result = new SearchContact((Id)o.get('Id'),(String)o.get('Name'),(Id)o.get('AccountId'),(String)o.get('Account.Name'),(String)o.get('Phone'),(String)o.get('Email'),(Id)o.get('OwnerId'),(String)o.get('Owner.Alias'),(Boolean)o.get('Active__c'),(Id)o.get('Broker_Number__c'),(String)o.get('Broker_Number__r.Name'),(String)o.get('Account.Firm__c'));
	ContactResults.add(result);
}

 

 

I keep getting an error that 'Account.Name' is not a valid field for Contact. How am I supposed to retrieve the Account Name, Owner Alias, etc.?

 

Thanks.

sylar20sylar20
I guess you will have to query account database and lookup with AccountId from Case sObject.
AAMAAM

Thanks for the reply. I ended up 'getting' the Objects within the loop and subsequently retrieving the individual fields:

 

for(sObject o : Database.query(QueryString))
{
	sObject Acct = o.getSobject('Account'); 
	sObject Owner = o.getSobject('Owner');
	sObject Dist = o.getSObject('Broker_Number__r');
				
	String AccountName = (String)Acct.get('Name');
	String OwnerAlias = (String)Owner.get('Alias');
	String BrokerNumber = (String)Dist.get('Name');
	String FirmName = (String)Acct.get('Firm__c');
				
	SearchContact result = new SearchContact((Id)o.get('Id'),(String)o.get('Name'),(Id)o.get('AccountId'),AccountName,(String)o.get('Phone'),(String)o.get('Email'),(Id)o.get('OwnerId'),OwnerAlias,(Boolean)o.get('Active__c'),(Id)o.get('Broker_Number__c'),BrokerNumber,FirmName);
	ContactResults.add(result);
}