How would one turn the enums used in an EF Core database context into lookup tables and add the relevant foreign keys?
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
We can use Enum. GetName static method to convert an enum value to a string. The following code uses Enum. GetName static method that takes two arguments, the enum type and the enum value.
You can use an enum in your code and have a lookup table in your db by using a combination of these two EF Core features:
Here below a data model example:
public class Wine { public int WineId { get; set; } public string Name { get; set; } public WineVariantId WineVariantId { get; set; } public WineVariant WineVariant { get; set; } } public enum WineVariantId : int { Red = 0, White = 1, Rose = 2 } public class WineVariant { public WineVariantId WineVariantId { get; set; } public string Name { get; set; } public List<Wine> Wines { get; set; } }
Here the DbContext
where you configure value conversions and data seeding:
public class WineContext : DbContext { public DbSet<Wine> Wines { get; set; } public DbSet<WineVariant> WineVariants { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=wines.db"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<Wine>() .Property(e => e.WineVariantId) .HasConversion<int>(); modelBuilder .Entity<WineVariant>() .Property(e => e.WineVariantId) .HasConversion<int>(); modelBuilder .Entity<WineVariant>().HasData( Enum.GetValues(typeof(WineVariantId)) .Cast<WineVariantId>() .Select(e => new WineVariant() { WineVariantId = e, Name = e.ToString() }) ); } }
Then you can use the enum values in your code as follow:
db.Wines.Add(new Wine { Name = "Gutturnio", WineVariantId = WineVariantId.Red, }); db.Wines.Add(new Wine { Name = "Ortrugo", WineVariantId = WineVariantId.White, });
Here is what your db will contain:
I published the complete example as a gist: https://gist.github.com/paolofulgoni/825bef5cd6cd92c4f9bbf33f603af4ff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With