When should enumerations stored in a database be used, and when is an enumeration in code?

What is the best way to store listings? For example, I have a Person face that has the Sex property. The first option I can think of is a table that stores values ​​and enumeration names (1 for Male and 2 for Female), and then in the Person table to store int values. The second option is to have an enumeration in the code with the corresponding int values ​​and store int values ​​in the Person table. The last option is to repeat the listing in the code and save the string value. For example, Man with sex "Man."

Which approach is better and when?

+3
source share
7 answers

, .

, : , . , ; . :

| Id | Value  |
---------------
| 1  | Male   |
| 2  | Female |

// FK from the table above to the table containing all your data, and in code:

enum Gender { Male = 1, Female = 2 }

?
F.E. Bitmasking! , , . , .

+5

, , .

, , , Visa Mastercard. , Discover Amex, , , .

+1

( ) : . enum int , int int, .

, : , . , , .

+1

. - , . , () , .

, , , . , .

, (1), M, F , , , , , ( , ).

, , , . "2" , "", , , , , development - .

+1

, . Visual Studio, T4 (Text Template Transformation Toolkit) ( .tt). / , . tt , " " # , .

+1

, , .., .

0

, .

Person
Name   |Age   |Gender |FK_Country_ID|
-------|------|-------|-------------|
varchar|int   |bit    |int          |

Country
CountryID|Country|
---------|-------|
int      |varchar|

Person 0.* ----- 1 Country

A foreign key constraint ensures that your data is valid when pasting or updating in a database. Hard-coded enumeration will force you to recompile your code later. It is better to practice reading values ​​for foreign keys and dynamic search.

0
source

Source: https://habr.com/ru/post/1775617/