I am able to convert an enum
to a string
with the following code. However, it only stores ONE of the selected values. In the case where TWO values are selected, it is truncated when I store it using NHibernate.
Here is my code:
MyEnum { One, Two, Three, Four, Five }
private static readonly string[] myEnum =
Enum.GetNames(typeof(MyEnum));
public string MyProperty
{
get {
var value = new MyEnum();
int i = (int)value;
return i >= 0 && i < myEnum.Length ?
myEnum[i] : i.ToString(); }
set {
Record.MyProperty= value ==
null ? null : String.Join(",", value); }
}
Record
is just public virtual string MyProperty { get; set; }
Can anyone provide a sample of how I would store, for example in comma-separated form, multiple enum
's that are selected (e.g., "One, Two, Five" are selected by the user and all three are stored in the DB)?
UPDATE:
I am trying to do this in the get{}
:
foreach (int i in Enum.GetValues(typeof(MyEnum)))
{
return i >= 0 && i < myEnum.Length ? myEnum[i] : i.ToString();
}
but am getting a not all code paths return a value
error.
QUESTION UPDATE:
If I did this with two string
's:
part.MyProperty = record.MyProperty;
Using IEnumerable<MyEnum>
answer below from @Jamie Ide won't work because I cannot convert string
to MyEnum
.
How would I write that last part to get the IEnumerable<MyEnum>
code from @Jamie Ide in the answer below to work?