Home > Dynamics CRM 2011 > Get Value fields of Lookup and OptionSet in CRM 2011

Get Value fields of Lookup and OptionSet in CRM 2011

Most of the times in Data migration we will be getting reference names instead of Guid. Here is the block of code to get the Guid based on the name. Pass the entity logical name, attribute name and attribute value and get the Guid.

static Guid GetGuidIDByName(string entityName, string NameAttribute, string Name)


QueryExpression qe = new QueryExpression(entityName);

qe.ColumnSet =new ColumnSet(newstring[] { NameAttribute });

FilterExpression fe = new FilterExpression();

fe.Conditions.Add(new ConditionExpression(NameAttribute, ConditionOperator.Equal, Name));

qe.Criteria = fe;

EntityCollection returnEntities = ICommonLogic.GetService().RetrieveMultiple(qe);

if (returnEntities != null)


if (returnEntities.Entities.Count > 0) return returnEntities.Entities[0].Id;


return Guid.Empty;


Following block of code will give the Optioion value based on option name passed of the OptionSet

static int GetOptionsSetValue(string entityName, string attributeName, string optionname)


RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest{

EntityLogicalName = entityName,LogicalName = attributeName,RetrieveAsIfPublished =true};

RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)ICommonLogic.GetService().Execute(retrieveAttributeRequest);

PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

int optionValue = -1;

foreach (OptionMetadata oMD in optionList)


if(oMD.Label.UserLocalizedLabel.Label == optionname)


optionValue = oMD.Value.Value;break;



return optionValue;


  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: