What is the best method of storing an Enum in a Database using C# And Visual Studio and MySQL Data Connector.
I am going to be creating a new project with over 100 Enums, and majority of them will have to be stored in the database. Creating converters for each one would be a long winded process therefore I'm wondering if visual studio or someone has any methods for this that I haven't heard off.
If you need store in DB string values of enum field, better do like show below. For example, it can be needed if you are using SQLite, which don`t support enum fields.
We store ours as ints or longs and then we can just cast 'em back and forth. Probably not the most robust solution, but that what we do.
we are using typed DataSets, so, for example:
A DB first approach can be used by creating a consistent table for each enum where the Id column name matches table name. It's advantageous to have enum values available within the database to support foreign key constraints and friendly columns in views. We are currently supporting ~100 enum types scattered throughout numerous versioned databases.
For a Code-First preference, the T4 strategy shown below could probably be reversed to write to the database.
Each table can be imported into C# using a T4 template (*.tt) script.
And finally, the somewhat gnarly T4 script (simplified from numerous workarounds). It will need to be customized to your environment. A debug flag can output messages into the C#. There is also a "Debug T4 Template" option when right clicking the .tt file. EnumGenerator.ttinclude:
Hopefully the entity framework will someday support a combination of these answers to offer the C# enum strong typing within records and database mirroring of values.
Works like a charm! No need to convert (int)Enum or (Enum)int in code. Just use the enum and ef code first will save the int for you. p.s.: "[EnumDataType(typeof(PhoneTypes))]" attribute is not required, just an extra if you want additional functionality.
Alternatively you can do: