I am new to EF Core, and am trying to seed an enum.
According to Data Seeding, this feature is new to EF Core 2.1.
I reviewed several solutions including this SO solution by Blake Mumford, but this doesn't work for me since an enum is not a reference type.
My goal (with the help from migrations) is to have the Category enum to be populated in a new SQL table called Category, and have my Payment table contain a column that references the Category table as a foreign key.
Any help would be greatly appreciated. Thanks.
public partial class Payment
{
public int PaymentId { get; set; }
public DateTime PostedDate { get; set; }
public string Vendor { get; set; }
public decimal Amount { get; set; }
public virtual Category Category { get; set; }
}
public enum Category
{
Restaurants,
Groceries,
[Display(Name = "Home Goods")]
HomeGoods,
Entertainment
}
public partial class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Error: The type Category must be a reference type in order to use it as parameter TEntity in the
// genric type or method ModelBuilder.Entity<TEntity>()
modelBuilder.Entity<Category>().HasData(Category.Restaurants,
Category.Groceries,
Category.HomeGoods,
Category.Entertainment);
}
}
This is what I did hopefully it will work with your environment.
Environment
Project Framework
Nugets:
Implementation
Add OnModelCreating
public partial class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Error: The type Category must be a reference type in order to use it as parameter TEntity in the
// genric type or method ModelBuilder.Entity<TEntity>()
modelBuilder.Entity<UserRole>().HasData(EnumFunctions.GetModelsFromEnum<UserRole, UserRoleEnum>());
}
}
Create a Generic Enum Function
public static class EnumFunctions
{
public static IEnumerable<TModel> GetModelsFromEnum<TModel, TEnum>() where TModel : IEnumModel<TModel, TEnum>, new()
{
var enums = new List<TModel>();
foreach (var enumVar in (TEnum[])Enum.GetValues(typeof(TEnum)))
{
enums.Add(new TModel
{
Id = enumVar,
Name = enumVar.ToString()
});
}
return enums;
}
}
Create an Interface
public interface IEnumModel<TModel, TModelIdType>
{
TModelIdType Id { get; set; }
string Name { get; set; }
}
Apply the interface to the model
[Table("UserRoles")]
public class UserRole : IEnumModel<UserRole, UserRoleEnum>
{
[Key]
public UserRoleEnum Id { get; set; }
public string Name { get; set; }
}
Add your migration
PM> add-migration SeedUserRoleTable
You should see the migration added
Update the database with the seeded info
PM> update-database