In this question, I discovered that enum changes are not handled by Entity Framework migrations. In fact, enum changes don't even result in a model changed error, so you can change enums at will with no controls.
Enum changes that result in different int values, such as order changes or removals, can effectively render the database data invalid, since the meaning of the stored integer is now wrong.
In order for Migrations to work, you have to manually execute custom SQL that changes the changed enum values.
The problem is, the developer has to remember to do this, and if there was an oversight then effective data corruption can occur.
How can someone put into place checks against this? Is it possible to, in the event an enum changes, throw a model change error or something like this?
Enum constants are implicitly static and final and you can not change their value once created.
You can change default values of enum elements during declaration (if necessary).
In Entity Framework, this feature will allow you to define a property on a domain class that is an enum type and map it to a database column of an integer type. Entity Framework will then convert the database value to and from the relevant enum as it queries and saves data.
You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type. Specify the type after enum name as : type .
A similar problem with enums exists in .Net when you move them out to a different Project to be used as a library:
http://bytes.com/topic/c-sharp/answers/271483-q-why-casting-enum#post1086722
Try it - enums in general are surprisingly brittle. The answer is to always assign an explicit value to your enums, to prevent both problems. This allows you to still leverage their core value (clear names instead of magic numbers and a little more to type safety in method arguments), but prevents you from quietly breaking everything.
You can enforce this policy with code reviews or post-commit hooks via a regex.
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