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
I am a well seasoned developer with 18 years experience in the industry and have been working on C# since .Net 1 made its debut, which is since 2002 and remember all the hardcore work that needed to be done and has seen how it evolved. I have written multitudes of solutions in .Net for many customers and always learn something new.
Needles to say, my repertoire does not start and end with .Net and includes tech knowledge from database, servers, applications across various streams, not just Microsoft technologies.
In the future I will attempt to hand some of my knowledge down to the community, since it has helped me so many times over the years.