Created
December 1, 2020 20:43
-
-
Save randyburden/9a83ce1191a8249ccc5d55e91143f043 to your computer and use it in GitHub Desktop.
Entity Framework Enumeration Class Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EmailType | |
{ | |
// Provides enum-like behavior while the persisted | |
// reference/lookup/enum table provides referential integrity | |
public static readonly EmailType Welcome = new EmailType | |
{ | |
Id = 1, | |
Name = "Welcome" | |
}; | |
[DataMember] | |
[Required] | |
public long Id { get; set; } | |
[DataMember] | |
[Required] | |
[MaxLength(100)] | |
public string Name { get; set; } | |
} | |
public class EmailLog | |
{ | |
[DataMember] | |
[ForeignKey("EmailType")] | |
[Required] | |
[MaxLength(100)] | |
public long EmailTypeId { get; set; } | |
[DataMember] | |
public EmailType EmailType { get; set; } | |
[DataMember] | |
[Required] | |
[MaxLength(254)] | |
public string FromEmailAddress { get; set; } | |
[DataMember] | |
[Required] | |
[MaxLength(254)] | |
public string ToEmailAddress { get; set; } | |
// ... | |
} | |
public class MyDbContext : DbContext | |
{ | |
public MyDbContext(DbContextOptions<MyDbContext> options) | |
: base(options) | |
{ | |
} | |
public DbSet<EmailLog> EmailLogs { get; set; } | |
public DbSet<EmailType> EmailTypes { get; set; } | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
// Don't generate an Id as this is a reference/lookup/enum table | |
modelBuilder.Entity<EmailType>().Property(p => p.Id).ValueGeneratedNever(); | |
} | |
} | |
public static class DbInitializer | |
{ | |
public static void Seed(MyDbContext context) | |
{ | |
// We can directly reference the static Welcome EmailType and have | |
// EF seed this entry into the EmailType reference/lookup table | |
context.EmailTypes.Add(EmailType.Welcome); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment