Enums and Lookup Tables with EF Code First

With EntityFramework’s support for enums, there is no longer any need to include lookup tables in the model. But I do want to have them in the database for integrity, even with code first.

I’ve been thinking for some time about to handle enums with code first. The idea behind code first is to be able to write the code as close as possible to how object oriented code is normally written. For enums that means that the enum definition itself is the constraint that is used to ensure that only valid values are used in the code.

For databases it would be possible to use a column constraint, but the normal way is to use a lookup table where the valid values are present. Any column in the database mapped against the enum type is then a foreign key to the lookup table to ensure integrity of the data.

What I would prefer is a solution where the lookup table is present in the database, but not mapped against any entity in the code.

[Flags] on Enums Make ToString() Smart

Putting the [Flags] attribute on an enum changes ToStrings behaviour. It generates a comma separated list.

I’ve used enums a lot. I’ve occasionally used the [Flags] attribute too. But I’ve never paid attention to how ToString() changes behaviour when the [Flags] attribute is added. Not until a couple of days ago, when I learnt something new (to me at least) and useful. The [Flags] attribute will make ToString() return a comma separated list of the flags set.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.