Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Customizing EF Core tables using EF Core 2.0+
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
public DbSet<OrderItem> OrderItems { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
// Customizations must go after base.OnModelCreating(builder)
builder.ApplyConfiguration(new ApplicationUserConfig());
builder.ApplyConfiguration(new OrderItemConfig());
// Imagine a ton more customizations
public class ApplicationUserConfig : IEntityTypeConfiguration<ApplicationUser>
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
// Override nvarchar(max) with nvarchar(15)
builder.Property(u => u.PhoneNumber).HasMaxLength(15);
// Make the default table name of AspNetUsers to Users
public class OrderItemConfig : IEntityTypeConfiguration<OrderItem>
public void Configure(EntityTypeBuilder<OrderItem> builder)
// Make the default column type datetime over datetime2(for some reason).
builder.Property(o => o.DateTimeOrdered).HasColumnType("datetime");
// Make the default value 1 for the Quantity property
builder.Property(o => o.Quantity).HasDefaultValue(1);
// Make the Primary Key associated with the property UniqueKey
builder.HasKey(o => o.UniqueKey);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment