存储枚举数据库最好的方法 [英] Best method to store Enum in Database

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

问题描述

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



我将要创建一个新项目超过100枚举​​,并且其中大部分将要被存储在数据库中。为每一个创建的转换器将是一个长篇大论的过程,因此我想知道如果Visual Studio或有人为这个,我还没有听说过任何方法。


解决方案

  [必需的] 
公共虚拟INT PhoneTypeId
{
得到
{
收益率( INT)this.PhoneType;
}

{
PHONETYPE =(PhoneTypes)值;
}
}
[EnumDataType(typeof运算(PhoneTypes))]
公共PhoneTypes PHONETYPE {搞定;组; }

公共枚举PhoneTypes
{
移动= 0,
首页= 1,
工作= 2,
传真= 3,
。其他= 4
}

工程就像一个魅力!无需(INT)或枚举(枚举)INT转换成代码。只需使用枚举和EF代码首先将保存INT为您服务。 PS:[EnumDataType(typeof运算(PhoneTypes))属性不是必需的,只是如果你想要更多的功能额外



另外,你可以这样做:



  [必需的] 
公共虚拟INT PhoneTypeId {搞定;组; }
[EnumDataType(typeof运算(PhoneTypes))]
公共PhoneTypes PHONETYPE
{
得到
{
回报(PhoneTypes)this.PhoneTypeId;
}

{
this.PhoneTypeId =(int)的值;
}
}


What is the best method of storing an Enum in a Database using C# And Visual Studio and MySQL Data Connector.

I am going to be creating a new project with over 100 Enums, and majority of them will have to be stored in the database. Creating converters for each one would be a long winded process therefore I'm wondering if visual studio or someone has any methods for this that I haven't heard off.

解决方案

    [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
}

Works like a charm! No need to convert (int)Enum or (Enum)int in code. Just use the enum and ef code first will save the int for you. p.s.: "[EnumDataType(typeof(PhoneTypes))]" attribute is not required, just an extra if you want additional functionality.

Alternatively you can do:

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

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

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