Skip to content

Instantly share code, notes, and snippets.

@scottsauber
Last active October 17, 2017 11:27
Show Gist options
  • Save scottsauber/77a1427bde3b38cf96fed87aaabd2e92 to your computer and use it in GitHub Desktop.
Save scottsauber/77a1427bde3b38cf96fed87aaabd2e92 to your computer and use it in GitHub Desktop.
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)
{
base.OnModelCreating(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
builder.ToTable("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