C# – Easy and fast way to get CRM entity name

cdynamics-crm-2011sdk

When retrieving a CRM entity including all attributes, in some cases some of the attributes with the type EntityReference have no name. In that case the ID of the reference is set but its Name property is null.

I have to use the name for some evaluation. Thus I was trying to query that referenced entity to get its name. The problem is, that the attribute that contains the entity name differs for different entity types.

(e.g. for Account it's "name", for Incident it's "title" and for other types it's "somePrefix_name_or_so")

Is there an easy way to get the entity name (Name property of an entity reference) using the CRM-SDK and a query?

Additional details:
The code is located in a CRM plugin. There the pre/post image normally contains all attributes, but in some cases during an update, (nearly) all entity references lose their names. The attributes in the dictionary are still there including the EntityReference objects. Only the Name property of the EntityReference instances is null.

My approach so far:

  • Retrieve entity in plugin
  • Get specific attribute (type: EntityReference)
  • Get name of that EntityReference
    • if that name is null, do a query to get that name (help! How?)
  • Use that name in some logic

Best Answer

For this you need to have EntityMetadata of the entity for which you have EntityReference. Then you can take EntityMetadata.PrimaryNameAttribute property, it contains name of the attribute of primary name. Given that attribute name you can obtain what you want. See more info about this property here: http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.metadata.entitymetadata.primarynameattribute.aspx