Wednesday, 25 February 2015

Retrieve CRM business Entities

To retrieve CRM business entities, you will be require to retrieve metadata information through RetrieveAllEntitiesRequest. 
 After retrieving the metadata, you will get complete list of entities listed in CRM whether it is system, business or custom entity. You can use the following code given below:

               RetrieveAllEntitiesRequest req = new RetrieveAllEntitiesRequest();

               req.EntityFilters = EntityFilters.Entity;

               req.RetrieveAsIfPublished = true;
       
               RetrieveAllEntitiesResponse response=
                                     (RetrieveAllEntitiesResponse)service.Execute(req);


                foreach (EntityMetadata currentEntity in response.EntityMetadata)
                          {
                                 string oEntity = "";
                                  // oEntity will provide you the name of Entities
                                  oEntity = currentEntity.SchemaName;                          
                           }

As you might be aware there are 325 entities(approx) in default CRM so you must not be interested in each and every Entities to list in. For this purpose there are many properties which are available in class
RetrieveAllEntitiesRequest which we can use as to filter the list, such as


               foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                           //property used to filter the entities list
                            if (currentEntity.IsValidForAdvancedFind.HasValue &&
                                currentEntity.IsValidForAdvancedFind.Value &&
                                currentEntity.CanBeRelatedEntityInRelationship.Value &&
                                currentEntity.CanBePrimaryEntityInRelationship.Value &&
                                currentEntity.CanTriggerWorkflow.Value &&
                                currentEntity.CanCreateViews.Value &&
                                currentEntity.CanCreateForms.Value &&
                                currentEntity.CanCreateCharts.Value &&
                                currentEntity.CanCreateAttributes.Value)
                            {
                                string oEntity = "";
                                oEntity = currentEntity.SchemaName;
                             }
                        }

If you can see i have used some of the filters such as IsValidForAdvancedFind, CanCreateViews, CanCreateForms etc which basically filter your list to almost 40 42 list of business entities. you can use more filters if you wish to filter the list further.

Thanks