Last active
October 17, 2017 11:27
-
-
Save scottsauber/77a1427bde3b38cf96fed87aaabd2e92 to your computer and use it in GitHub Desktop.
Customizing EF Core tables using EF Core 2.0+
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 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 | |
} | |
} |
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 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"); | |
} | |
} |
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 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