Entity Framework Core 2 – Entity Type Configuration

 

Entity Framework Core 2 was released on August 14th. It brought new features.

On this article I will explain one of them : Entity Type Configuration

Each entity can be configured in a separate class from the DbContext, functionality removed in EF Core 1 while it was present in previous versions

In Entity Framework Core 1, we had to configure our entities in our DbContext directly, in OnModelCreating method exactly, we had to override it and put entities configuration within like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   builder.HasKey(x => x.ProductID);
   builder.HasOne(e => e.Details).WithOne( o=> o.Product).HasForeignKey(e => e.ProductID);
   builder.Property(x => x.Cost).HasColumnName("StandardCost");
   builder.HasQueryFilter(o => o.Cost > 0);
   builder.ToTable("Product");

   base.OnModelCreating(modelBuilder);
}

For your information it’s still working in Entity Framework Core 2.

Entity Framework Core 2 brings the possibility to externalize this configuration by implementing the Interface: IEntityTypeConfiguration<T> 

Example:

public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
   public void Configure(EntityTypeBuilder<Product> builder)
   {
      builder.HasKey(x => x.ProductID);
      builder.HasOne(e => e.Details).WithOne( o=> o.Product).HasForeignKey<ProductDetail>(e => e.ProductID);
      builder.Property(x => x.Cost).HasColumnName("StandardCost");
      builder.HasQueryFilter(o => o.Cost > 0);
      builder.ToTable("Product");
   }
}

Usage :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.HasDefaultSchema("Production");
   modelBuilder.ApplyConfiguration(new ProductConfiguration());

   base.OnModelCreating(modelBuilder);
}

That’s it!

Cleaner isn’t it ? 😉