2017

Wednesday, February 8, 2017

MS Dynamics CRM and Dynamics 365: Find Entity Logical name by only using Record primary key(GUID)


As a integration developer I've been always forced to find solutions for complex problems, eventually every time I gain knowledge and found solutions in the end (sometimes multiple for a single problem).

A week back I had faced an issue in my work environment when I was integrating an application with Dynamics CRM. The issue here is, I have a primary key value of a particular entity record and I need to find the entity logical name.

So, obviously when we first hear this problem, most of us would have found the solution like below,
  1. Fetch all entities metadata.
  2. Iterate through them and execute a retrieve request on each entity for the given value(primary key as GUID).
  3. The execution which doesn't gives the exception is the answer. 
The above is the one and only way here, but what about the performance? If the UI has to refresh based on this how much time the user has to wait? Is it actually solves the problem. It does solve the problem but there arises new problems. So it'll be better to optimize the solution which I'm going to explain in here.

We will be making couple of calls to CRM instead of bunch of calls to get the desired answer i.e., the logical name of the entity which belongs to the given value.

  1. First call to CRM, get all entities metadata by specifying the EntityFilters as Entity.
  2. Create a list of Retrieve requests with retrieved entities and given value (GUID).
  3. Second CRM call, in Dynamics CRM we've a special request called ExecuteMultiple which is capable of executing maximum of 5000 calls by default. Create a ExecuteMultiple Request instance and add the created retrieve requests to the RequestCollection of the EntityMultiple request. And execute it in CRM.
  4. The response will not give you an exception but will give you a response with collection of responses. In which except one response all other will have IsFaulted=true.
  5. Third Part is finding the succeeded response. You can use LINQ to find which is easy to write for developers.
Now you've got the pseuodocode of a better approach (I'll not it as a best approach, 'coz there are people living stronger than the strongest person). I'll soon post the example code in my github page.

Thank you and all the best. 😃