Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randyburden/9a83ce1191a8249ccc5d55e91143f043 to your computer and use it in GitHub Desktop.
Save randyburden/9a83ce1191a8249ccc5d55e91143f043 to your computer and use it in GitHub Desktop.
Entity Framework Enumeration Class Pattern
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