Compare Page Revisions
« Older Revision - Back to Page History - Newer Revision »
AddSpaces
public abstract class EnumDbEntity<TEnum> { [Required] public TEnum Id { get; set; } [Required, StringLength(100)] public string Value { get; set; } /* TODO: Override this method where needed, especially if the derived class as extra fields. */ public virtual EnumDbEntity<TEnum> InitForSeeding(TEnum value, bool addSpaces) { Id = value; Value = EnumHelper<TEnum>.GetDisplayValue(value, addSpaces); return this; } } public static class EnumDbEntityExtensions { public static void SeedEnumTable<TEnum, TEntity>(this IDbSet<TEntity> dbSet) where TEnum : struct, IConvertible where TEntity : EnumDbEntity<TEnum>, new() { if (!typeof(TEnum).IsEnum) throw new ArgumentException("TEnum must be an enumerated type"); var itemValues = (TEnum[])Enum.GetValues(typeof(TEnum)); foreach (var itemValue in itemValues) { //dbSet.AddOrUpdate(a => a.Id, new TEntity { Id = itemValue, Value = EnumHelper<TEnum>.GetDisplayValue(itemValue) }); var item = new TEntity(); item.InitForSeeding(itemValue, addSpaces); dbSet.AddOrUpdate(a => a.Id, item); } } } /* Reference * https://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via-mvc-razor-code */ public static class EnumHelper<T> where T : struct, IConvertible { public static string GetDisplayValue(T value) { var fieldInfo = value.GetType().GetField(value.ToString()); var descriptionAttributes = fieldInfo.GetCustomAttributes( typeof(DisplayAttribute), false) as DisplayAttribute[]; //if (descriptionAttributes[0].ResourceType != null) // return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name); if (descriptionAttributes == null) return string.Empty; return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString().AddSpaces(); } }
public enum OrderStatusEnum { Active, Inactive } public class OrderStatus : EnumDbEntity<OrderStatusEnum> { }
context.OrderStatuses.SeedEnumTable<OrderStatusEnum, OrderStatus>();
ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.