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?
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.
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.
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).
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.
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.
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:
Enum:
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