Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I store Enum ID/values in the database or a C# enumeration?

Say my database tables have columns like UserType, SalesType, etc.

Should I have database tables with UserTypeID, userTypeName or should I just create a C# enumeration?

like image 462
mrblah Avatar asked Apr 26 '09 15:04

mrblah


People also ask

Should enums be stored in database?

By keeping the enum in your database, and adding a foreign key on the table that contains an enum value you ensure that no code ever enters incorrect values for that column. This helps your data integrity and is the most obvious reason IMO you should have tables for enums.

Where should I declare enum?

If only your class members use the enum it is preferable to declare the enum inside the class. It is more intutive for users of the class, it helps the user to know that the enum will only be used by the class.

How are enum values stored?

A standard enum is usually implemented as an int32, the compiler will handle your enum as a synonym of int32 . Once a list of values is created for a enumeration those values are stored as literals against their display name(access name given at the time of declaration of enum).

Can enum values be compared in C?

How to compare Enum values in C#? Enum. CompareTo(Object) Method is used to compare the current instance to a specified object and returns an indication of their relative values.


2 Answers

What's wrong with both? If value's are user-defined or changing, definitely enum will not be suitable.

If values are strictly non-changing (such as gender), you can have them as enums for ease of reference in the application and also in the DB as separate table to enforce foreign keys and as a reference.

like image 103
mmx Avatar answered Nov 08 '22 05:11

mmx


It depends. I listed a few pros and cons for each approach below. In general, I strongly prefer enums if the application needs to use a value to make decisions. As Mehdrad mentioned, you can use both approaches but it requires extra effort to keep the lists in sync.

Lookup tables:

  • Referential integrity can be enforced through foreign keys
  • Easy to add or remove existing values
  • Table can be extended to add additional fields (active flag, etc.)
  • Requires additional class if using business objects
  • Easy to use value and description in reports

Enum:

  • Check constraint can enforce data integrity
  • Best choice if code needs to use value for branching (e.g. x == SalesType.Web vs. x == "WEB")
  • Requires software release to change values
  • Cannot display description in SQL queries (without CASE)
  • Enum may not be appropriate for display in UI (there are workarounds)
like image 34
Jamie Ide Avatar answered Nov 08 '22 04:11

Jamie Ide