2

Trying to write some test code for a custom object and its controller class. I noticed that one of my methods which depends on the ownership of an object was bugging out and I discovered that Owner.Id and OwnerId are returning different values. Are they supposed to be different? which one am I suppoed to use? Here is an example.

    Conversation__C convA = new Conversation__C();
    convA.FromNumber__c = '1231231231';
    convA.ToNumber__c = '2342342342';
    insert convA;
    List<Conversation__c> conversationsT = [Select OwnerId, Owner.Id from Conversation__c ];
    for (Conversation__c c : conversationsT)
        System.debug(c.Owner.Id + ' ' + c.OwnerId);

returns

09:38:01:200 USER_DEBUG [68]|DEBUG|null mySalesforceID 

The strange thing is that both return the same data in production!

1 Answer 1

6

You should use OwnerId. I am not sure why there is a difference in values, and will try to reproduce. But there is no reason to introduce a cross-object reference when all you need is the Id value itself.

One example why Owner.Id is less preferable:

system.debug(c.get('OwnerId')); // works
system.debug(c.get('Owner.Id')); // fails

You can get the cross-reference to work, but it's definitely more complicated.

Another reason it's less preferable is that you can't set it that way. Might as well be consistent.

c.OwnerId = idValue; // works
c.Owner.Id = idValue; // cannot update in this manner

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.