Expense__c expenses = [select Owner.Name, Contact__r.Name, from Expense__c];

for (Expense__c i : expenses)
    String expOwner = String.valueOf(i.get('Owner.Name'));
    String contact = String.valueOf(i.get('Contact__r.Name'));

I get following error: Invalid field Owner.Name for Expense__c

How do I retrieve values of Owner Name and Contact Name?

2 Answers 2


With static SOQL (where the SObject structure is known at compile-time) you can do it like this:

Expense__c expenses = [select Owner.Name, Contact__r.Name, from Expense__c];

for (Expense__c e : expenses)
    String expOwner = e.Owner.Name;
    String contact = e.Contact__r != null ? e.Contact__r.Name : null;

Note if some relationships are optional you need to check for nulls to avoid NullPointerExceptions in your code.

If using dynamic SOQL you need to use getSObject first then get.


If the expense is the child in a master-detail relationship there will be no "Owner" field available as it is owned by the parent

As an aside, it would be helpful when asking questions if you posters would specify the line where the error is occurring or when it is occurring (compile vs runtime). There are two possible places where that message could occur.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .