65.9K
CodeProject is changing. Read more.
Home

DbEnum

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

May 10, 2017

MIT
viewsIcon

7241

This is the DbEnum that is used with the EntityFrameworkCore Seeding article

Introduction

DbEnum is just a class that can build up the enum to eventually seeded to the database.  Unfortunately I could not find anything else but to derive TEnum from struct.  If there is a better way, please shout.

I found a similar construct years ago, but it has evolved over time to the extend that the inner workings does not reflect the original article.

This is used for EntityFrameworkCore Seeding: https://www.codeproject.com/Articles/1186323/EntityFrameworkCore-Seeding-Component

public interface IDbEnum
{
    int Id { get; set; }
}

public class DbEnum<TEnum> : IDbEnum where TEnum : struct
{
    private Enum _;
    private string _display;

    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id
    {
        get { return Convert.ToInt32(_); }
        set { _internalSet((Enum)Enum.ToObject(typeof(TEnum), value)); }
    }

    public string Description
    {
        get { return _.ToString(); }
        set { _internalSet((Enum)Enum.Parse(typeof(TEnum), value)); }
    }

    public string Display
    {
        get { return _display = (!string.IsNullOrEmpty(_display) ? _display : _.GetDisplayString()); }
        set { _display = value; }
    }

    private void _internalSet(Enum value)
    {
        if (!_.Equals(value))
        {
            _ = value;
        }
    }

    public DbEnum()
    {
        _ = (Enum)Enum.Parse(typeof(TEnum), default(TEnum).ToString());
    }

    protected DbEnum(Enum value)
    {
        _ = value;
    }

    public TEnum ToEnum()
    {
        return (TEnum)Convert.ChangeType(_, typeof(TEnum));
    }

    public static implicit operator DbEnum<TEnum>(Enum value)
    {
        return new DbEnum<TEnum>(value);
    }

    public static implicit operator TEnum(DbEnum<TEnum> value)
    {
        return value.ToEnum();
    }
}

EnumHelper @ https://www.codeproject.com/Reference/1186338/EnumHelper-for-DbEnum