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

标签 c# database visual-studio database-design enums

使用 C# 和 Visual Studio 以及 MySQL Data Connector 在数据库中存储枚举的最佳方法是什么。

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

最佳答案

    [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。 p.s.: “[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;
        }
    }

关于c# - 在数据库中存储枚举的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2646498/

相关文章:

c# - vs 2017 中的 IIS Express 502 错误

database - 标记内容系统 - 使用 i18n

database - sqlplus 无法在 linux 64 上启动

c# - WPF DragDrop : Window. ShowModal() 挂起 Windows 资源管理器

java - Hibernate有没有类似于Nhibernate "Mapping by code"的东西

java - 如何解决java.sql.SQLException : No suitable driver found for jdbc:derby:

c++ - 同时使用基于范围的for循环和do while循环时VS2013编译错误

c# - 多部分标识符 "TextBox1.Text"无法在 C# ASP.NET 中绑定(bind)?

c# - 匹配所有美国电话号码格式的正则表达式

c# - JOIN 对象集合的多个属性的正确方法?