CRM 2011 – How to select an Id in a QueryExpression

As I have been converting all my LINQ queries into QueryExpressions so my plugins can work on CRM 2011 Online.  It was quite annoying to find LINQ wasn’t compatible with CRM 2011 online and the sandbox.  I don’t really understand why, I assume it’s something to do with the transactions.

Today I was trying to select the id of an entity and use an entity reference  object to make sure I had got the right one.

The basic scenario is I had an entity which had a Entity Reference to another object and I wanted to use that to return the whole entity.

I initially had a mind blank trying to remember what the ID field was (and it’s not just id) but then I worked it out that it’s the entity name with id added to end of it.  So I was looking for a hosk_candidate entity, I add the id to the end to get


The other little gotcha was when you use the EntityReference to get the id you have to do

 public hosk_candidate getCandidateQuery(IOrganizationService service, EntityReference id)
                ConditionExpression condition1 = new ConditionExpression();

                condition1.AttributeName = "hosk_candidateid";
                condition1.Operator = ConditionOperator.Equal;

                FilterExpression filter1 = new FilterExpression();

                QueryExpression query = new QueryExpression("hosk_candidate");
                query.ColumnSet = new ColumnSet(true);
                // query.ColumnSet = new AllColumns();

                EntityCollection result1 = service.RetrieveMultiple(query);
                IEnumerable<hosk_candidate> candidates = result1.Entities.Cast<hosk_candidate>();
                hosk_candidate candidate = (hosk_candidate)returnOne(candidates);

                return candidate;

            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
                // You can handle an exception here or pass it back to the calling method.

2 thoughts on “CRM 2011 – How to select an Id in a QueryExpression

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s