Entity PrimaryKey using Metadata Service

Sometimes we need to get the Entity ID for the any custom entity, by default the entityid equals to +"id". So we can get the id for any dynamic entity as

Entity.Properties["entitylogicalname"+"id"];
But this is a snippet for achieving the same using metadata service.


// Get the Primary key from CRM Entity
public string GetEntityPrimaryKey(String EntityName)
{
// Metadata Service
Func myMetaService = () =>
{
// Create an authentication token.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = "OrgName";
token.AuthenticationType = 0;

// Create the metadata Web service;
MetadataService metadataService = new MetadataService();
metadataService.Url = "http://:/MSCRMServices/2007/MetadataService.asmx";
metadataService.CrmAuthenticationTokenValue = token;
metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
metadataService.PreAuthenticate = true;
return metadataService;
};

// Create the request
RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();
entityRequest.RetrieveAsIfPublished = false;
entityRequest.LogicalName = EntityName;
entityRequest.EntityItems = EntityItems.EntityOnly;

// Execute the request
RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)myMetaService().Execute(entityRequest);

// Access the retrieved entity
EntityMetadata retrievedEntityMetadata = entityResponse.EntityMetadata;
return retrievedEntityMetadata.PrimaryKey;
}