Wednesday, February 18, 2009

Get Dynamic Entity Primary Attribute Guid Example


Example by CrmSdk


public Guid GetDynamicEntityPrimaryAttributeGuid(DynamicEntity entity)
{
    if (entity != null)
    {
        string strPrimaryKeyAttributeName = entity.Name.ToLower() + "id";
        return ((Microsoft.Crm.Sdk.Key)entity.Properties[strPrimaryKeyAttributeName]).Value;
    }
    return Guid.Empty;
}

Example by Web Service

public Guid GetDynamicEntityPrimaryAttributeGuid(DynamicEntity entity)
{
    if (entity != null)
    {
        string strPrimaryKeyAttributeName = entity.Name.ToLower() + "id";
        for (int i = 0; i < entity.Properties.Length; i++)
        {
            if (entity.Properties[i].Name.ToLower() == strPrimaryKeyAttributeName)
            {
                KeyProperty property = (KeyProperty)entity.Properties[i];
                return property.Value.Value;
            }
        }
    }
    return Guid.Empty;
}

1 comment:

Bryce G said...

That is not a reliable method of retrieving the id property. You should be looping through the Properties looking for one that is typeof(Key).

For instance serviceappointment has a primary id called activityid property.