Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

c# - OptionSetValue behaving like an integer

I recently experienced an OptionSetValue behaving like an integer in a method of my plugin. Previously, and with all other OptionSetValues, to retrieve the integer value, I have used the pattern:

localIntegerVariable = (new_myEntity.GetAttributeValue<OptionSetValue>("new_myOptionSetAttribute")).Value;

That no longer works in the one of the methods of the plugin. If i treat it like an integer, it works.

localIntegerVariable = (new_myEntity.GetAttributeValue<int>("new_myOptionSetAttribute"));

Strangely enough, in the main section of the same plugin before I retrieve the pre image entity, I treat the same attribute as an OptionSetValue like below and it works just fine.

int incominglocalIntegerVariable = temp.GetAttributeValue<OptionSetValue>("new_myOptionSetAttribute") == null ? _OSV_Empty : temp.GetAttributeValue<OptionSetValue>("new_myOptionSetAttribute").Value;

I have verified that the definition of new_myOptionSetAttribute in the entities.cs file is an OptionSetValue. I have also verified that the definition in CRM is an OptionSet value.

Has anyone experienced this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Below code will throw exact error, because you are trying to assign right side int value to left side OptionSetValue variable:

InvalidCastException: Unable to cast object of type 'System.Int32' to type 'Microsoft.Xrm.Sdk.OptionSetValue'

OptionSetValue localIntegerVariable;

localIntegerVariable = (new_myEntity.GetAttributeValue<OptionSetValue>("new_myOptionSetAttribute")).Value;

In this case localIntegerVariable should be int, because .Value will be giving you int datatype result.

To maintain same datatype, either change it to

int localIntegerVariable;

localIntegerVariable = (new_myEntity.GetAttributeValue<OptionSetValue>("new_myOptionSetAttribute")).Value;

or

OptionSetValue localIntegerVariable;

localIntegerVariable = new_myEntity.GetAttributeValue<OptionSetValue>("new_myOptionSetAttribute");

Last example is better, as it checks null check before accessing .Value using expression temp.GetAttributeValue<OptionSetValue>("new_myOptionSetAttribute") == null ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...