My latest project included integrating employees into Active Directory via 3rd party API. I successfully did so, but afterward, my team requested some sort of log to monitor the integration.
The activity log I created included to an ActionType int that was related to an enum. For transparency, I wanted to transfer those enums into a small table, that way those values could be easily available to our team, all of whom have SQL query skills, but are not all developers.
A simple idea and solution, to migrate enums to a table using Entity Framework, just not something I had done using CodeFirst. Here’s how I got it working.
The log I set up is pretty straight forward and included an ActionType int.
[Table("Activity", Schema = "MyApp")] public class MyAppActivity { [Key] public int Id { get; set; } public int ActionType { get; set; } public DateTime UpdateDateTime { get; set; } = DateTime.Now; public string Response { get; set; } public bool Success { get; set; } //payload }
That integer, ActionType, is tied to ActionTypeEnum:
public enum ActionTypeEnum { DEPENDENCY_NOT_FOUND = 1, INVALID = 2, SKIP = 3, CREATE = 4, UPDATE = 5, REHIRE = 6, TERMINATE = 7 }
I created the table ActionType to hold these values:
[Table("ActionType", Schema = "MyApp")] public class ActionType { [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)] public ActionTypeEnum Id { get; set; } public string Name { get; set; } }
Now, to populate ActionType:
public class MyAppContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("CONN_STRING_HERE"); } protected override void OnModelCreating(ModelBuilder builder) { foreach (var e in Enum.GetValues(typeof(ActionTypeEnum)).Cast<ActionTypeEnum>()) { builder.Entity<ActionType>().HasData(new ActionType { Id = e, Name = e.ToString() }); } } public DbSet<MyAppActivity> MyAppActivity { get; set; } public DbSet<ActionType> ActionType { get; set; } }
Quick and easy and helps my team query the data they need without need for my help.