在数据库中存储枚举值的最佳方法 - String或Int [英] Best way to store enum values in database - String or Int

查看:1094
本文介绍了在数据库中存储枚举值的最佳方法 - String或Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一些枚举
,它们在一些类中用作属性类型。

I have a number of enums in my application which are used as property type in some classes.

存储这些值的最佳方法是什么在数据库中,作为String或Int?

What is the best way to store these values in database, as String or Int?

FYI,我也将使用流畅的Nhibernate映射这些属性类型。

FYI, I will also be mapping these attribute types using fluent Nhibernate.

示例代码:

public enum ReportOutputFormat
{
    DOCX,
    PDF,
    HTML
}

public enum ReportOutputMethod
{
    Save,
    Email,
    SaveAndEmail
}

public class ReportRequest
{
    public Int32 TemplateId
    {
        get { return templateId; }
        set { templateId = value; }
    }
    public ReportOutputFormat OutputFormat
    {
        get { return outputFormat; }
        set { outputFormat = value; }
    }

    public ReportOutputMethod OutputMethod
    {
        get { return outputMethod; }
        set { outputMethod = value; }
    }
}


推荐答案

两者都有优势。如果您按照Integer值存储它们,那么您必须在项目中仔细编辑枚举。如果某些方式枚举元素的整数值被重新定义,您的所有数据将被损坏。但是它将是最快/最小的数据类型。

Both have advantages. If you store them by their Integer value, then you must be careful editing your enumeration later on in your project. If somehow the integer values for the enumeration elements get redefined, all your data will be corrupted. But it will be the fastest/smallest datatype to use.

如果你使用字符串表示,你不会有重新定义值的问题,只要你不更改枚举中的元素的名称。但是字符串在你的数据库中占用更多的空间,并且在使用中可能会更昂贵一些。

If you use the string representation you'll not have the redefined value problem for as long as you don't change the name of the elements in the enumeration. However strings take up more space in your database and are probably a bit more costly in use.

最后,我没有确定的赢家。

At the end, there's no definitive winner I guess.

编辑

使用Integer值可能是最好的方法。你可以通过自己设置每个元素的值来克服枚举元素的'重定义值'问题。确实是Kevin的一个好建议。

Using the Integer value might be the best way. You can overcome the 'redefined value' problem for the enumeration elements, by setting the value for each element yourself. Indeed a good suggestion from Kevin.

这篇关于在数据库中存储枚举值的最佳方法 - String或Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆