Hello Experts,
I am trying to create an Option Set in an entity programmatically via the CRM SDK.
The code below works for Option Sets which are not Global, but when it encounters an Attribute with underlying Global Option Set it throws this Error:
"Error: You cannot create a system option set directly through the SDK. Only custom option sets can be created directly through the SDK."
OR
"Error: You cannot set Options property for an Attribute that links to an existing Global OptionSet."
My Code:
foreach (AttributeMetadata attr in attributes)
{
/* Will process Attributes which: */
if (attr.IsCustomAttribute != null && attr.IsCustomAttribute.Value == true && /* Are Custom Attributes (Created by User) */
attr.AttributeType.HasValue && attr.AttributeType.Value.ToString() == "Picklist" && /* AND are of Type Option Set */
!logicalNamesToIgnore.Contains(attr.LogicalName)) /* AND are NOT in the IGNORE list */
{
EnumAttributeMetadata enumAttr = (EnumAttributeMetadata)attr;
CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
{
EntityName = ChildEntityLogicalName,
Attribute = enumAttr
};
service.Execute(createAttributeRequest);
Console.WriteLine($"Attribute Created ---> {enumAttr.LogicalName}");
}
}
Do you have any suggestion on how to create it? Do I need to create a RelationshipRequest ? Any good articles help!
Thanks!
My Solution:
foreach (AttributeMetadata attr in attributes)
{
/* Will process Attributes which: */
if (attr.IsCustomAttribute != null && attr.IsCustomAttribute.Value == true && /* Are Custom Attributes (Created by User) */
attr.AttributeType.HasValue && attr.AttributeType.Value.ToString() == "Picklist") /* AND are of Type Option Set */
{
EnumAttributeMetadata enumAttr = (EnumAttributeMetadata)attr;
enumAttr.MetadataId = new Guid(); /* This is to avoid GUID collision */
if (enumAttr.OptionSet.IsGlobal == false) /* If it is NOT Global Option Set */
{
enumAttr.OptionSet.MetadataId = new Guid(); /* This is to avoid GUID collision */
enumAttr.OptionSet.Name = ChildEntityLogicalName enumAttr.OptionSet.Name.Substring(ParentEntityLogicalName.Length); /* Replace Parent LogicalName with Child LogicalName */
}
else
{
Console.WriteLine("Global Option Set Name ---> " enumAttr.OptionSet.Name);
enumAttr.OptionSet.Options.Clear();
}
CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
{
EntityName = ChildEntityLogicalName,
Attribute = enumAttr
};
service.Execute(createAttributeRequest);
Console.WriteLine($"Attribute Created ---> {enumAttr.LogicalName}");
}
}