在数据库中存储枚举的最佳方法

Mic*_*han 58 c# database enums database-design visual-studio

使用C#和Visual Studio以及MySQL数据连接器在数据库中存储枚举的最佳方法是什么.

我将创建一个包含100多个枚举的新项目,其中大部分都必须存储在数据库中.为每个人创建转换器将是一个漫长的过程,因此我想知道视觉工作室或某人是否有任何方法,我没有听说过.

Joa*_*eme 59

    [Required]
    public virtual int PhoneTypeId
    {
        get
        {
            return (int)this.PhoneType;
        }
        set
        {
            PhoneType = (PhoneTypes)value;
        }
    }
    [EnumDataType(typeof(PhoneTypes))]
    public PhoneTypes PhoneType { get; set; }

public enum PhoneTypes
{
    Mobile = 0,
    Home = 1,
    Work = 2,
    Fax = 3,
    Other = 4
}
Run Code Online (Sandbox Code Playgroud)

奇迹般有效!无需在代码中转换(int)Enum或(Enum)int.只需使用enum和ef代码,首先会为你保存int.ps:"[EnumDataType(typeof(PhoneTypes)]]"属性不是必需的,如果你想要额外的功能,只需要一个额外的属性.

或者你可以这样做:

[Required]
    public virtual int PhoneTypeId { get; set; }
    [EnumDataType(typeof(PhoneTypes))]
    public PhoneTypes PhoneType
    {
        get
        {
            return (PhoneTypes)this.PhoneTypeId;
        }
        set
        {
            this.PhoneTypeId = (int)value;
        }
    }
Run Code Online (Sandbox Code Playgroud)


Mua*_*Dib 10

我们将我们存储为整数或长期,然后我们可以来回投射它们.可能不是最强大的解决方案,而是我们所做的.

我们使用的是类型化的DataSet,例如:

enum BlockTreatmentType 
{
    All = 0
};

// blockTreatmentType is an int property
blockRow.blockTreatmentType = (int)BlockTreatmentType.All;
BlockTreatmentType btt = (BlockTreatmentType)blockRow.blocktreatmenttype;
Run Code Online (Sandbox Code Playgroud)

  • 这种接缝就像一个可接受的解决方案 我会把这个问题暂时搁置,看看人们想出了什么.我假设您手动设置枚举的int值以防止订单/基数更改? (2认同)

tru*_*oda 8

如果您需要将枚举字段的字符串值存储在数据库中,最好如下所示。例如,如果您使用不支持枚举字段的 SQLite,则可能需要它。

[Required]
public string PhoneTypeAsString
{
    get
    {
        return this.PhoneType.ToString();
    }
    set
    {
        PhoneType = (PhoneTypes)Enum.Parse( typeof(PhoneTypes), value, true);
    }
}

public PhoneTypes PhoneType{get; set;};

public enum PhoneTypes
{
    Mobile = 0,
    Home = 1,
    Work = 2,
    Fax = 3,
    Other = 4
}
Run Code Online (Sandbox Code Playgroud)