Is there a standard way to using Enums in EF code-first? There seems to be some examples making use of a wrapper class for the enum.
However, I would like to be able to define the enum and have the enum values also seeded into the database using the database initializer. There doesn't seem to be much point in defining the enum and creating a wrapper, if I then have to seed the database table manually from the enum.
Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…
Data seeding is the process of populating a database with an initial set of data. There are several ways this can be accomplished in EF Core: Model seed data. Manual migration customization. Custom initialization logic.
Install Entity FrameworkRight click on your project name and select Manage NuGet Packages. Go to Browse and Select Entity Framework then click Install button to install Entity Framework on your project.
Unfortunately, enums
are not natively supported on EF 4.1. Here's one rather known article on how to deal with them: Faking enums on EF 4. It does, however, require a wrapper.
There's a simpler way to map enums in EF 4 however: just create an int property on your class to represent the int value of the enum. That's the property that EF should map, then have a "mini wrapper" property to allow you to use the enum.
public class Appointment { public int ID { get; set; } public string Description { get; set; } // This property will be mapped public int DayOfWeekValue { get; set; } public DayOfWeek Day { get { return (DayOfWeek) DayOfWeekValue; } set { DayOfWeekValue = (int) value; } } } public enum DayOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
On generating the database, EF will happily ignore any type it doesn't know how to map, but the int property will be mapped.
Note: This is taken directly from my answer to another enum
and EF
question: EF 4.1 Code First - map enum wrapper as complex type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With