数据库和 O/RM 中的枚举
假设我希望表 Regions
中的条目具有类型,例如城市、国家等。假设我将使用 O/RM(我的 NHibernate案件) ? 我看到两个选项:
- 在 C# 总线层中使用类型的枚举,并将类型作为
tinyint
存储在表中。 - 拥有一个包含类型标识符(字符串或整数)的查找表
RegionTypes
并在Regions
表中引用它们。
从数据库的角度来看,第二种方法似乎更合理,因为我有外键约束,而且我可以有关于区域类型的附加数据,例如城市是国家/地区的子类型(并且因为我使用的是 SQL Server 2008空间特征,我实际上需要这些信息来进行空间操作)。 然而,从 C# 的角度来看,我基本上必须有一个实体 RegionType
,并在每次我想将它分配给一个区域时从数据库加载它(据我了解 NHibernate 不会这样做)如果我将其存储在查找表中,则不允许我将该类型设为枚举)。 对于这样一个简单的任务来说,这有点乏味,因为区域类型基本上是固定的,不太可能改变。
其他类型怎么样,比如 DayOfWeek
,它们不太可能改变或具有其他属性,它们是否应该有自己的查找表和实体?
Suppose I want entries in the table Regions
to have a type, e.g. a city, a country etc. What's the accepted way of storing this type, assuming I'll be using O/RM (NHibernate in my case) ? I see two options:
- Have an enum in the C# bussines layer with the types and store the type as a
tinyint
in the table. - Have a lookup table
RegionTypes
with the type identifiers (strings or ints) and reference them in theRegions
table.
The second approach seems more reasonable from the database point of view, since I have foreign key constraints, plus I can have additional data about the region types, e.g. a city is a child type for country (and since I'm using SQL Server 2008 spatial features, I actually need this information for spatial manipulations). However, looking from the C# point of view, I'll basically have to have an entity RegionType
and load it from the database every time i want to assign it to a region (as I understand NHibernate wouldn't allow me to make the type an enum if I store it in a lookup table). This is a little tedious for such a simple task, knowing that region types are basically fixed and unlikely to change.
What about other types, like DayOfWeek
which are unlikely to ever change or have additional properties, should they have their lookup tables and entities ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般规则是,如果您确定用户永远不会更改一组值,则使用枚举。 否则最好使用查找表。
General rule is to use Enums if you are sure that set of values will never be changed by user. Otherwise it's better to use lookup table.
使用查找表的原因之一是在菜单或其他内容中显示可能值的常见用例。 查询查找表很容易,但如果枚举被硬编码在数据库数据类型或约束中,或者在 C# 枚举中,则就不那么容易了。
One reason to use lookup tables is the common use case of displaying the possible values in a menu or something. It's easy to query a lookup table, but less easy if the enum is hard-coded in a database data type or constraint, or in a C# enum.
不过,我通常会选择后一种选择,不过,我将创建一种通用类型的设置,其中多种类型的项目可以存储在同一个表中,这样我就不会得到 15 种类型的表。 基础知识是这样的
I usually go with the latter option, though, I'll create a generic sort of set up where items of multiple types can be stored in the same table so that I don't end up with 15 types tables. The basics are something like this