Entity Framework Core Fluent API

Fluent API in Entity Framework Core (EF Core) is a way to configure the model classes. Fluent API uses the Modelbuilder instance to configure the domain model. We can get the reference to the ModelBuilder, when we override the onmodelcreating method of the DbContext. The ModelBuilder has several methods, which you can use to configure the model. These methods are more flexible and provide developers with more power to configure the database than the EF Core conventions and data annotation attributes

What is Fluent API

A Fluent interface is a way of implementing an object-oriented API in a way that aims to provide for a more readable code Fluent interface resembles natural language making it easier to read and write. You can read about Fluent Interface from this link

Fluent Interface gives two distinct advantageous

  • Method chaining
  • More readable API Code 

The ModelBuilder class uses the Fluent API to build the model.

ModelBuilder

The ModelBuilder is the class which is responsible for building the Model.

The ModelBuilder builds the initial model from the entity classes that have DbSet Property in the context class, that we derive from the DbContext class.

It then uses the conventions to create primary keys, Foreign keys, relationships etc.

Next, it will look for the Data Annotations attributes to further configure the model.

We can use the ModelBuilder to further configure the model. To do that we need to get the reference to the ModelBuilder in our context. To do that we need to override the OnModelCreating method of the DbContext object.

OnModelCreating

As mentioned above, the DBContext builds the model using the ModelBuilder class.

But, before freezing the model, it calls the OnModelCreating method and passes the instance of the ModelBuilder to it. This gives us a chance to further configure the model.

The initialization does not happen when EF Core creates the DBContext. It happens when we use the Context for the first time.

The EF Core also caches the resulting model. It uses the Cached model whenever it creates a new instance of the Context.

We can override the OnModelCreating method in our code as shown in the example below. We get the reference to the Modelbuilder in our overridden class. Use the ModelBuilder along with the fluent API to configure our model.

ModelBuilder class includes important properties and methods to configure the domain model.

Fluent API Example in EF Core

Open Visual Studio 2019 and create C# -> .NET Core -> Console App (.NET Core). Name the project as EFCoreFluentAPI

Install the following packages

Create the models.cs under the root folder and add the employee class as shown below

Next, Create context class EFContext under the root folder

As mentioned earlier, we need to override the OnModelCreating method and use the instance of the ModelBuilder to configure the model

And then use the ModelBuilder instance. In the following code, we are invoking the HasDefaultSchema method to change the schema of the database to admin.

Next, we need to use the migrations to update/create the database as shown below

You can see that the DbContext creates the Employee table under the Admin schema

Fluent API in EF Core Entity Configuration

Method chaining is one of the main features of EF Core Fluent API. For Example, the following code renames table as mstEmployee and defines EmployeeID as Primary Key

There are several methods available in EF Core Fluent API. These methods broadly classified into the three categories

  • Model wide configuration (database)
  • Entity Configuration (table)
  • Property configuration

Model-wide configuration

The Model wide properties are applied to the entire model. For Example, HasDefaultSchema defines the schema for every entity in the model.

The ModelBuilder class exposes several methods to configure the model. Some of the important methods are listed below

MethodDescription
HasDefaultSchemaConfigures the default schema that database objects should be created in, if no schema is explicitly configured.
RegisterEntityTypeRegisters an entity type as part of the model
HasAnnotationAdds or updates an annotation on the model. If an annotation with the key specified in annotation already exists its value will be updated.
HasChangeTrackingStrategyConfigures the default ChangeTrackingStrategy to be used for this model. This strategy indicates how the context detects changes to properties for an instance of an entity type.
IgnoreExcludes the given entity type from the model. This method is typically used to remove types from the model that were added by convention.
HasDbFunctionConfigures a database function when targeting a relational database.
HasSequenceConfigures a database sequence when targeting a relational database.

Entity Configuration

The configuration of the entity (Table) is done using the method Entity. The following code is an example of how to configure the Primary Key using the HasKey method.

This method Entity returns the EntityTypeBuilder object to configure the entities. Some of the important methods available in the EntityTypeBuilder object are listed below

Fluent API in EF Core Entity Configuration
MethodDescription
IgnoreExclude the entity from the Model.
ToTableSets the table name for the entity type
HasKeySets the properties that make up the primary key for this entity type.
HasManyConfigures a relationship where this entity type has a collection that contains instances of the other type in the relationship.e
HasOneConfigures a relationship where this entity type has a reference that points to a single instance of the other type in the relationship.
HasAlternateKeyAdds or updates an annotation on the entity type. If an annotation with the key specified in annotation already exists its value will be updated
HasChangeTrackingStrategyConfigures the ChangeTrackingStrategy to be used for this entity type. This strategy indicates how the context detects changes to properties for an instance of the entity type.
HasIndexConfigures an index on the specified properties. If there is an existing index on the given set of properties, then the existing index will be returned for configuration.
OwnsOneConfigures a relationship where the target entity is owned by (or part of) this entity. The target entity key value is always propagated from the entity it belongs to.

Property Configuration

The EntityTypeBuilder object, which is explained above returns the Property Method. This method is used to configure the attributes of the property of the selected entity. The Property method returns the PropertyBuilder object, which is specific to the type being configured.

Fluent API in EF Core Property Configuration
MethodDescription
IgnoreExclude the Propery from the Model.
HasColumnNameConfigures database column name of the property
HasColumnTypeConfigures the database column data type of the property
HasDefaultValueConfigures the default value for the column that the property maps to when targeting a relational database.
HasComputedColumnSqlConfigures the property to map to a computed column when targeting a relational database.
HasFieldSpecifies the backing field to be used with a property.
HasMaxLengthSpecifies the maximum length of the property.
IsConcurrencyTokenEnables the property to be used in an optimistic concurrency updates
IsFixedLengthConfigures the property to be fixed length. Use HasMaxLength to set the length that the property is fixed to.
IsMaxLengthConfigures the property to allow the maximum length supported by the database provider
IsReguiredSpecifies the database column as non-nullable.
IsUnicodeConfigures the property to support Unicode string content
ValueGeneratedNeverConfigures a property to never have a value generated when an instance of this entity type is saved.
ValueGeneratedOnAddConfigures a property to have a value generated only when saving a new entity, unless a non-null, non-temporary value has been set, in which case the set value will be saved instead. The value may be generated by a client-side value generator or may be generated by the database as part of saving the entity.
ValueGeneratedOnAddOrUpdateConfigures a property to have a value generated when saving a new or existing entity.
ValueGeneratedOnUpdateConfigures a property to have a value generated when saving an existing entity.

Reference

  1. ModelBuilder API
  2. OnModelCreating

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top