Best method to store Enum in Database

前端 未结 10 1942
挽巷
挽巷 2020-12-12 12:42

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 E

相关标签:
10条回答
  • 2020-12-12 13:22

    You don't need to do anything if you want to store ints. Just map your property in EF. If you want to store them as strings use converter.

    Int (db type is smallint):

    public override void Configure(EntityTypeBuilder<MyEfEntity> b)
    {
        ...
        b.Property(x => x.EnumStatus);
    }
    

    String (db type is varchar(50)):

    public override void Configure(EntityTypeBuilder<MyEfEntity> b)
    {
        ...
        b.Property(x => x.EnumStatus).HasConversion<EnumToStringConverter>();
    }
    

    If you want to save your db data usage use smallint as a column in db. But data won't be human readable and you should set an index against every enum item and never mess with them:

    public enum EnumStatus
    {
        Active = 0, // Never change this index
        Archived = 1, // Never change this index
    }
    

    If you want to make data in db more readable you can save them as strings (e.g. varchar(50)). You don't have to worry about indexes and you just need update strings in db when you change enum names. Cons: column size gets data usage more expensive. It means if you got a table within 1,000,000 rows it might have an impact on db size and performance.

    Also as a solution you can use short enum names:

    public enum EnumStatus
    {
        [Display(Name = "Active")]
        Act,
        [Display(Name = "Archived")]
        Arc,
    }
    

    Or use your own converter to make names in db shorter:

    public enum EnumStatus
    {
        [Display(Name = "Active", ShortName = "Act")]
        Active,
        [Display(Name = "Archived", ShortName = "Arc")]
        Archived,
    }
    ...
    public override void Configure(EntityTypeBuilder<MyEfEntity> b)
    {
        ...
        b.Property(x => x.EnumStatus).HasConversion<MyShortEnumsConverter>();
    }
    

    More info can be found here: EF: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-types/enums EFCore: https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions

    0 讨论(0)
  • 2020-12-12 13:23

    Why not try separating the enums altogether from the DB? I found this article to be a great reference while working on something similar:

    http://stevesmithblog.com/blog/reducing-sql-lookup-tables-and-function-properties-in-nhibernate/

    The ideas in it should apply regardless of what DB you use. For example, in MySQL you can use the "enum" data type to enforce compliance with your coded enums:

    http://dev.mysql.com/doc/refman/5.0/en/enum.html

    Cheers

    0 讨论(0)
  • 2020-12-12 13:24

    If you need store in DB string values of enum field, better do like show below. For example, it can be needed if you are using SQLite, which don`t support enum fields.

    [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
    }
    
    0 讨论(0)
  • 2020-12-12 13:27

    In the end you will need a great way to deal with repetitious coding tasks such as enum converters. You can use a code generator such as MyGeneration or CodeSmith among many others or perhaps an ORM mapper like nHibernate to handle everything for you.

    As for the structure... with hundreds of enums I would first consider trying to organize the data into a single table that might look something like this: (pseudo sql)

    MyEnumTable(
    EnumType as int,
    EnumId as int PK,
    EnumValue as int )
    

    that would allow you to store your enum info in a single table. EnumType could also be a foreign key to a table that defines the different enums.

    Your biz objects would be linked to this table via EnumId. The enum type is there only for organization and filtering in the UI. Utilizing all of this of course depends on your code structure and problem domain.

    Btw, in this scenario you would want to set a clustered index on EnumType rather than leaving the default cluster idx that is created on the PKey.

    0 讨论(0)
提交回复
热议问题