Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Extension Method to Seed Enum Values into Database Table - Entity Framework Code First

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: Fri, Jun 02, 2017, 1:56 PM


References

The AddSpaces extension method can be found here.

Reusable Code

public abstract class EnumDbEntity<TEnum>
{
    [Required]
    public TEnum Id { get; set; }

    [Required, StringLength(100)]
    public string Value { get; set; }
}
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 = itemValue.ToString().AddSpaces() });

}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.