Fluent API - Applications and Configuration

27 January 2021 at 10:00 by ParTech Media - Post a comment

Fluent API interface, named by Eric Evans and Martin Fowler in 2005, is an object-oriented API. It is extensively used to increase the legibility of code by creating a domain-specific language. The ease in reading and writing comes with its resemblance to our natural languages. It provides more flexibility and versatility for configuration than the old and conventional data annotations. It helps the developers by giving them more capability to arrange the database.

In this post, we are going to understand the application of fluent API through a sample project.

Table of contents

  1. DBModebuilder Class
  2. Fluent API Sample Project
  3. Steps to change the schema using Fluent API
  4. Model wise configuration of DBModelbuilder
  5. Entity Configuration
  6. Property Configuration
  7. Wrapping Up

DBModelbuilder Class

The Entity Framework Fluent API uses the Fluent Interface. Fluent API gets carried out in the class called DBModelbuilder. DBModelBuilder is used to map Common Language Runtime (CLR) classes to a database schema. A code-based Entity Data Model (EDM) gets built in this way which often gets referred to as 'Code First'.

public class DbModelBuilder

The reference to DbModelBuilder class gets retrieved after overriding the OnModelCreating method of the DBContext Object.

Fig.- Code-First Workflow

Before DBContext initializes the model, the method DBModelbuilder Class gets called. This happens when the context gets created for the first time. At the time of initialization, DBContext initializes the instance named DbModelBuilder. Post this; it initializes all the domain classes. Then the OnModelCreating method gets called, and the reference moves to the DbModelBuilder.

Fluent API Sample Project

Tools Used in this Project:

Here are the steps -

  1. Open Visual Studio 2019.
  2. Go to File -> New -> Project.
  3. Select the required template Visual C# -> Windows -> Console Application.
  4. Name the project. In our case, we have named it EFFluentAPI.
  5. Click on OK to create the Project.
  6. Install the latest entity framework 6.4.4 from the NuGet Package Manager.
  7. To add a new file named employee.cs, you need to right-click on the project.

Adding the following employee model will do the job for you.

Then, you need to initialize the context class named EFContex in the root directory of the project.

Finally, in the Program.cs, you need to update the Main method.

After running the above code snippet, it will generate the EF6FluentAPI with a table named - Employee.

You can change the schema with Fluent API

Steps to change the schema using Fluent API

As we mentioned earlier, you have to eliminate the OnModelCreating method of the DBContext class. In this way, you can obtain the instance of the DbModelBuilder object.

After that, the HasDefaultSchema method of the DBModelBuilder object can be used to change the default schema of the database.

Then you can copy the code to the EFContext class:

The above method creates a table named employee with the schema name as "Admin.”

The DbModelBuilder class consists of several methods that are used to configure the domain model. These methods are created with the following points:

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

Model-wise configuration of DBModelbuilder

The DbModelBuilder class consists of the following properties/methods which is used to configure the model. Some of the most noticeable properties and methods are as follows:

  • HasDefaultSchema: This method is used to configure the default database schema name that is ideal for the model. It gets overridden at the entity level.
  • RegisterEntityType: This method is used to register an entity type that is considered a part of the model

Entity configuration

Entity configuration is done using Entity - TEntityType. This method returns the entitytypeconfiguration element that can be used for configuring the entities. Some of the important methods that are available in entitytypeconfiguration element are as follows:

  • ToTable: It helps to set the name of the table for the entity type
  • HasKey: Configures the primary key for the chosen entity type
  • HasMany: Configures more than one relationships for the selected entity type
  • HasOptional: This method is used to configure an optional relationship for the selected entity type. Allows you to save the Instances of the entity type to the database without the connection being specified. This method creates the nullable foreign key within the database.
  • HasRequired: This method configures a relationship that will be suitable for the selected entity type. It does not allow you to save the instances of the entity type without specifying the relationship. This method creates a non-null foreign key in the database.

Property configuration

It allows configuration to perform for an entity type inside a model. The Entity method on DbModelBuilder often extracts an EntityTypeConfiguration. Also, a custom type derived from EntityTypeConfiguration may even get registered through the configuration’s property on DbModelBuilder. The Property method then returns the configuration object, which is specific to the type that gets configured.

Here are the different property configuration -

  • HasColumnName: Configures database column name of the property
  • HasColumnOrder: This method gets used to configure the order in which the column is viewed in the database table. It also helps to create the composite primary key to specify the key order.
  • HasColumnType: Configures the database column which has the data type of the property
  • HasDatabaseGeneratedType: Used to configure how the values for the property are generated by the database
  • HasMaxLength: This method specifies the maximum length of the property.
  • HasParameterName: This method specifies the name of the parameter which will get used in stored procedures for this property.
  • IsConcurrencyToken: This method enables the property to get used for positive concurrency updates.
  • IsFixedLength: Configures the property to be of fixed length.
  • IsMaxLength: This method is used to configure the property to allow the maximum length which is supported by the database provider.
  • IsOptional: Specifies the database column as mutable
  • IsRequired: It is used to specify the database column as non-nullable.
  • IsUnicode: This method is used to configure the property to support Unicode string content.
  • IsVariableLength: Configures the property to be of variable length

Wrapping up

There are numerous reasons why Fluent API gets extensively used in projects which use the 'code-first' approach. It increases the readability of code as a prime Design perspective. It helps to emphasize the purpose of your code and also helps to handle complex concepts with ease.