Fluent API Configuration

EF Core's Fluent API provides methods for configuring various aspects of your model:

Configurations are applied via a number of methods exposed by the Microsoft.EntityFrameworkCore.ModelBuilder class. The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory. You can override this method to add your own configurations:

public class SampleContext : DbContext
{
    // Specify DbSet properties etc

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // add your own confguration here
    }
}

The term Fluent API refers to a pattern of programming where method calls are chained together with the end result being certainly less verbose and arguably more readable than a series of statements:

// series of statements
modelBuilder.Entity<Order>().Property(t => t.OrderDate).IsRequired();
modelBuilder.Entity<Order>().Property(t => t.OrderDate).HasColumnType("Date");
modelBuilder.Entity<Order>().Property(t => t.OrderDate).HasDefaultValueSql("GetDate()");

// fluent api chained calls
modelBuilder.Entity<Order>()
    .Property(t => t.OrderDate)
        .IsRequired()
        .HasColumnType("Date")
        .HasDefaultValueSql("GetDate()");

In this example, the DateCreated property of the Order entity is configured as Required (not nullable), is mapped to a SQL Server Date type and has a default value applied. Each method call returns a type that exposes its own set of methods which is what enables the chaining of methods. Often, the type returned from the method call is the same instance as the one on which the method is called. For example, the IsRequired method above is exposed by the PropertyBuilder class. The return type of this method is an instance of the PropertyBuilder class, so once the method has performed its task, it ends simply with return this;.

The Fluent API provides a larger range of configuration options than Data Annotation attributes. Fluent API configuration also facilitates cleaner code, in that the configuration can be kept separate from the domain classes.

Most examples in this guide show configurations being applied in the OnModelCreating method, but it is recommended to separate configurations out to individual files per entity - especially for larger models or ones that require a lot of configuration.

In previous versions of Entity Framework, this was accomplished by creating classes that implemented EntityTypeConfiguration<TEntity> and adding code to their constructor that performed the confguration. There are plans to introduce this kind of pattern to EF Core at some stage, but in the meantime some useful workaround ideas can be obtained from the relevant GitHub issue that tracks the topic.


Created:
Last updated: 14/03/2017 16:33:44
Proficiency Level: Beginner