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

大城市里の小女人 提交于 2019-12-19 05:37:29

问题


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?


回答1:


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.




回答2:


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)



回答3:


In my projects, I use my application dbscript to generate C# consts from database, so code always matches db values.

Of course, you only need to have C# enums if your code does something specific depending on the value of the Type field.




回答4:


If the list is stable enough to use an enum, then I would use an enum in your code plus a table in the database (make it a foreign key for data consistency).



来源:https://stackoverflow.com/questions/791030/should-i-store-enum-id-values-in-the-database-or-a-c-sharp-enumeration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!