[SalesForce] Determine sobject Type From Id Using SOAP API

I'm using C# and would like to determine the type of an sObject based on it's id.

I would like to pass an id to my app and have it return a list of accounts related to it. I need to identify the sobject type of the id so I can create a proper soql query for it. (If it's an Invoice__c do one query, if it's a Crazy_Custom_Grandchild__c do another, etc…)

I tried a .search() api call like this:

FIND {'001800000116UUiAAM'} IN Id FIELDS RETURNING Contact(Id, Phone, FirstName, LastName), 
Lead(Id, Phone, FirstName, LastName), Account(Id, Phone, Name)

but received a malformed query error because of the id field.

I don't want to have to do a whole bunch of try ... catch calls, there has to be a better way…

Best Answer

best solution I've come up with so far is to use .describeGlobal() like this:

DescribeGlobalResult dgr = binding.describeGlobal();
DescribeGlobalSObjectResult dgsr = dgr.sobjects.FirstOrDefault(x =>
    string.IsNullOrEmpty(x.keyPrefix) ? false : id.StartsWith(x.keyPrefix));

    if (dgsr != null)
    {
        switch (dgsr.name)
        {
            case "custom1__c":
                ...
                break;
            case "custom2__c":
                ...
                break;
            case "custom3__c":
                ...
                break;
            default:
                ...
                break;
        }
    }
Related Topic