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

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

问题描述

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

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

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

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
}

就像一个魅力!无需在代码中转换 (int)Enum 或 (Enum)int.只需先使用 enum 和 ef 代码即可为您保存 int .ps:[EnumDataType(typeof(PhoneTypes))]"属性不是必需的,如果你想要额外的功能,只需一个额外的.

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.

或者你可以这样做:

[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天全站免登陆