Retrieve entity-name from Object Type code in MSCRM using C#


//Find the Logical Name from the entity type code - this needs a reference to the Organization Service to look up metadata
public string GetEntityLogicalName(IOrganizationService service)
{
    var entityFilter = new MetadataFilterExpression(LogicalOperator.And);
    entityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode ", MetadataConditionOperator.Equals, this.EntityTypeCode));
    var propertyExpression = new MetadataPropertiesExpression { AllProperties = false };
    propertyExpression.PropertyNames.Add("LogicalName");
    var entityQueryExpression = new EntityQueryExpression()
    {
        Criteria = entityFilter,
        Properties = propertyExpression
    };

    var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
    {
        Query = entityQueryExpression
    };

    var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

    if (response.EntityMetadata.Count == 1)
    {
        return response.EntityMetadata[0].LogicalName;
    }
    return null;
}

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s