我想知道如何在我正在制作的CRM插件中获取OptionSet的字符串值。我以为我需要做的就是将int值传递给OptionSetValue,但这似乎不起作用。这是我的代码:
aBillingFrequencyCode = new OptionSetValue(myContract.BillingFrequencyCode.Value).ToString();
但是输出只是
Microsoft.Xrm.Sdk.OptionSetValue
有任何想法吗?
最佳答案
您可以检索OptionSet标签,而无需检索实体的所有元数据。我提供了两种方法。人们将使用IOrganizationService运行帐户的语言代码(LCID)。另一个允许您指定LCID。
请注意,如果您打算在代码中广泛使用它们,则可能需要考虑缓存该值以提高性能-这将取决于您的特定应用程序要求。
如果计划同时在单个实体上为多个选项集检索这些值,则应使用上面的Guido代码,并在一次调用中检索所有实体元数据,以减少对CRM进行调用的次数。因此,在某些情况下,我们的每个代码段都效率更高。
//This method will return the label for the LCID of the account the IOrganizationService is using
public static string GetOptionSetValueLabel(string entityName, string fieldName, int optionSetValue, IOrganizationService service)
{
var attReq = new RetrieveAttributeRequest();
attReq.EntityLogicalName = entityName;
attReq.LogicalName = fieldName;
attReq.RetrieveAsIfPublished = true;
var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;
return attMetadata.OptionSet.Options.Where(x => x.Value == optionSetValue).FirstOrDefault().Label.UserLocalizedLabel.Label;
}
//This method will return the label for the specified LCID
public static string GetOptionSetValueLabel(string entityName, string fieldName, int optionSetValue, int lcid, IOrganizationService service)
{
var attReq = new RetrieveAttributeRequest();
attReq.EntityLogicalName = entityName;
attReq.LogicalName = fieldName;
attReq.RetrieveAsIfPublished = true;
var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;
return attMetadata.OptionSet.Options.Where(x => x.Value == optionSetValue).FirstOrDefault().Label.LocalizedLabels.Where(l => l.LanguageCode == lcid).FirstOrDefault().Label;
}