Reputation: 3403
I have an enum for the days of the week:
public enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
I'm trying to store an array or list of selected DaysOfWeek in an entity model that is used to persist data in a database using EF code first:
public IEnumerable<DaysOfWeek> SelectedWeekendDays { get; set; }
which should hold one or more DaysOfWeek values, but this yields a null value when populated as:
SelectedWeekendDays = new List<DaysOfWeek> { DaysOfWeek.Sunday, DaysOfWeek.Saturday }
So my question is, how can selected enum values be stored in an entity model. Any help would be greatly appreciated.
Upvotes: 0
Views: 127
Reputation: 2880
If I am correct you should define it Flag attribute
[Flags]
public enum DaysOfWeek
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
And use Enum.HasFlag
to check enums selected
Upvotes: 0
Reputation: 3228
Assuming that property is in your ViewModel,you can go with this approach: in your POCO
class create a property like below and store the selected enum in there:
public DaysOfWeek SelectedEnum { get; set; }
Or if you want you can only store its numeric value
public int SelectedEnum { get; set; }
Update
For Multiple, you can create a int[] instead, so basically:
public int[] SelectedEnum { get; set; }
And Here how to populate it:
public int[] Population()
{
int[] Example = { Convert.ToInt32(DaysOfWeek.Sunday),
Convert.ToInt32(DaysOfWeek.Saturday), so on... };
return Example;
}
Upvotes: 1