FYI: I explicitly mean SQL Server 2000-8 and C#. So DBMSs with enum support like MySql is not the subject of my question.
I know this question has been asked multiple times in SO. But still, I see in answers that different approaches are taken to store enum values in db.
- Save enum as int in db and extract the enum value (or enum description attribute using reflection) in code:
this is the approach I usually use. The problem is when I try to query from database in SSMS, the retrieved data is hard to understand. - Save enum as string (varchar) in db and cast back to int in code.
Actually, this might the best solution. But (don't laugh!) it doesn't feel right. I'm not sure about the cons. (Except more space in db which is usually acceptable) So anything else against this approach? - Have a separate table in db which is synchronized with code's enum definition and make a foreign key relationship between your main table and the enum table.
The problem is when another enum value should be added later, Both code and db need to get updated. Also, there might be typos which can be a pain!
So in general when we can accept the overhead on db in 2nd solution, What would be the best way to store enum values in db? Is there a general definite design pattern rule about this?
Thanks.
3条答案
按热度按时间cfh9epnr1#
There is no definite design rule (that I know of), but I prefer approach #1.
EDIT: Chris in the comments had a good point: If you do go down the numeric approach, you should explicitly assign values so you can re-order them as well. For example:
hivapdat2#
One idea I've seen before which is your option 3 more or less
The database table table can have a trigger or check constraint to reduce risk of changes. It shouldn't have any write permissions because the data is tied to a client code release, but it adds a safety factor in case the DBA bollixes up
If you have other clients reading the code (which is very common) then the database has complete data.
wtlkbnrh3#
I referred to the answers here and on this question . I would like to summarize these answers and also add my perspective. So, here's what I think,
Option 1: Store the Enum values in a lookup table, but don't declare Enum in code
Option 2: Store the Enum values in a lookup table and also declare Enum in code
Option 3: Declare the Enum in code, but don't create a lookup table for it