Posts Tagged ‘sdk’

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;