Should I store my Enums at database level or in th

2019-05-03 17:29发布

I have a table, lets call it Objects. It has a predefined set of records looking like this:

ObjectId ObjectName

  1       Salmon
  2       Trout
  3       Seabass
  4       Shark

Etc..

So, this I would like to implement somehow as an enum. But what's the best way, implement it in the database creating tables for it or in the application logic in an CommonEnums codebehind file etc?

2条回答
闹够了就滚
2楼-- · 2019-05-03 18:14

We add them in both places, we use code generator to keep in sync the values.

The main values are in the Enum but the template automatically generates a script to update the DB

We also add a property to our entities to expose an enum property instead of the integer that is saved to the DB

Edit: Adding an example of how to do it (In VB.NET:

    <EnumDbTableInfo("TableName", "keyColumn", "descColumn")> _
    Public Enum CasoImportacion As Short

        <Description("")> _
        Normal = 0

        <Description("The First Description")> _
        FirstRealValue = 1

        <Description("A second one")> _
        AnotherValue = 2

        <Description("Third Description")> _
        LastValue = 3


End Enum

Later an EnumHelper class take the classes that has the attribute EnumDbTableInfo and generates the script to update the DB

Best Regards

查看更多
唯我独甜
3楼-- · 2019-05-03 18:20

I generally use a foreign key (lookup) table in the db if I will need to join the tables to get a text description of the code for display to a user, say for a report, or ad hoc querying or something. If the value is strictly internal - that is, never displayed to anyone - or is used only in my code where I can translate it as needed, I would just put a constraint on the field and skip the foreign key table.

查看更多
登录 后发表回答