Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

DbEnum

0.00/5 (No votes)
9 May 2017 1  
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here