Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling enum changes in Entity Framework 5

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?

like image 739
Chad Levy Avatar asked Aug 13 '12 20:08

Chad Levy


People also ask

Can you change enums?

Enum constants are implicitly static and final and you can not change their value once created.

Can you change the value of an enum in C?

You can change default values of enum elements during declaration (if necessary).

What is enum in Entity Framework?

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.

Can enums hold strings?

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 .


1 Answers

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.

like image 109
Chris Moschini Avatar answered Nov 03 '22 17:11

Chris Moschini