Fluent API Configurations in Entity Framework

Fluent API Configurations in Entity Framework

In this article, I am going to discuss Fluent API Configurations in Entity Framework Code First Approach with Examples. Please read our previous article where we discussed TimeStamp Attribute in Entity Framework with Examples.

Fluent API Configurations in Entity Framework

Like the Data Annotation Attribute, the Entity Framework provides Fluent API which we can also use to configure the domain classes which will override the default conventions which is followed by the Entity Framework. The Entity Framework Fluent API is based on the Fluent API design pattern (also known as Fluent Interface Design Pattern) where the result is formulated by method chaining. So, before proceeding further and understanding, the Fluent API in Entity Framework, we first need to understand the Fluent Interface Design Pattern and Method Chaining.

What is the Fluent Interface Design Pattern?

The main objective of the Fluent Interface Design Pattern is to apply multiple methods to an object by connecting them with dots (.) without having to re-specify the object name each time. Let us understand How to Implement a Fluent Interface Design Pattern with an example. Let us say, we have the following Student class.

What is the Fluent Interface Design Pattern?

Now, if we want to consume the above Student class, then we generally, create an instance of the Student class and then we need to set the respective properties of the Student class as shown in the below image.

What is the Fluent Interface Design Pattern?

The Fluent Interfaces Design Pattern simplifies our object consumption code by making our code more simple, readable, and understandable. Is not it nice to set the Student object properties as shown in the below image?

Fluent API Configurations in Entity Framework Code First Approach with Examples

If we consume the object like the above interface, then it is something like speaking a sentence that would really make the class consumption code more simple and more readable, and more understandable. Now, the next big thing that we need to understand is how to implement this. To implement this, we have something called Method Chaining.

What is Method Chaining?

Method chaining is nothing but a technique or process where each method, set the value of a property of an object and then returns an object and all these methods can be chained together to form a single statement. In order to implement method chaining, first, we need to create a wrapper class around the Student class as shown in the below image.

What is Method Chaining?

As you can see in the above FluentStudent class, here we have created methods for each Student property. First, we create an instance of Student Class, and then, in each method, we are setting the value of the respective Student Property. Further, notice that the return type of each method is set to the FluentStudent and this is important, and because of this, we can call subsequent methods using the dot operator. Now the above fluent interface is going to be consumed by the client. So, with the above FluentStudent class in place, now the client code looks as shown below.

Fluent API Configurations in Entity Framework

The Complete Example code of Fluent Interface Design Pattern:

Whatever we have discussed so far is given in the below example. The following example shows how to implement Fluent Interface Design Pattern in C#.

using System;
namespace FluentInterfaceDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            FluentStudent student = new FluentStudent();
            student.StudentRegedNumber("BQPPR123456")
                   .NameOfTheStudent("Pranaya Rout")
                   .BornOn("10/10/1992")
                   .StudyOn("CSE")
                   .StaysAt("BBSR, Odisha");

            Console.Read();
        }
    }

    public class Student
    {
        public string RegdNo { get; set; }
        public string Name { get; set; }
        public DateTime DOB { get; set; }
        public string Branch { get; set; }
        public string Address { get; set; }
    }
    
    public class FluentStudent
    {
        private Student student = new Student();
        public FluentStudent StudentRegedNumber(string RegdNo)
        {
            student.RegdNo = RegdNo;
            return this;
        }
        public FluentStudent NameOfTheStudent(string Name)
        {
            student.Name = Name;
            return this;
        }
        public FluentStudent BornOn(string DOB)
        {
            student.DOB = Convert.ToDateTime(DOB);
            return this;
        }
        public FluentStudent StudyOn(string Branch)
        {
            student.Branch = Branch;
            return this;
        }
        public FluentStudent StaysAt(string Address)
        {
            student.Address = Address;
            return this;
        }
    }
}

Now, I hope you understand the Fluent Interface Design Pattern. With this kept in mind, let us proceed and try to understand Fluent API in Entity Framework Code First Approach.

Configuring Fluent API in Entity Framework

The point that you need to remember is Fluent API configuration can only be applied when Entity Framework builds the models from your domain classes. That means you can use Fluent API Only when you are working with Entity Framework Code First Approach. In Entity Framework 6, the DbModelBuilder class acts as a Fluent API using which we can configure many different things. It provides more options for configurations than Data Annotation attributes. In this case, you need to override the OnModelCreating method of DbContext class in your context class to inject the Fluent API configurations something like the below in Entity Framework. You can see, we are calling many methods using the same modelBuilder object using the dot (.) operators which is nothing but method chaining.

Configuring Fluent API in Entity Framework

Note: The point that you need to remember is, in Entity Framework, you can configure a domain class using both Data Annotation Attributes and Fluent API at the same time. In this case, Entity Framework API will give precedence to Fluent API over Data Annotations Attributes.

Fluent API Configurations in Entity Framework:

In Entity Framework, the Fluent API configures the following things of a model class.

  1. Model-Wide Configuration: Configures the default Schema, entities to be excluded in database mapping, etc.
  2. Entity Configuration: Configures the Primary Key, Index, table name, one-to-one, one-to-many, many-to-many relationships, etc.
  3. Property Configuration: Configures property to column mappings such as column name, making column as NULL or NOT NULL, Foreign key, the data type of the column, size of the column, concurrency column, etc.

Now, let us proceed and try to understand the different methods available in each configuration.

Model-Wide Configurations in Entity Framework
  1. HasDefaultSchema(): It configures the default database schema name. This default database schema name is used for database objects that do not have an explicitly configured schema name.
  2. ComplexType(): It configures the class as a complex type, not a database table.
Entity Configurations in Entity Framework
  1. HasIndex(): It configures the index property for the entity type.
  2. HasKey(): It configures the primary key property(s) for the entity type.
  3. HasMany(): It configures more than one relationship i.e. multiple one-to-many or many-to-many relationships.
  4. HasOptional(): It configures an optional relationship that will create a nullable foreign key in the database.
  5. HasRequired(): It configures the required relationship which will create a non-nullable foreign key column in the database.
  6. Ignore(): It configures that the class or property should not be mapped to a table or column in the database.
  7. Map(): It allows advanced configuration related to how this entity type is mapped to the database schema. By default, any configuration will also apply to any type derived from this entity type. Derived types can be configured via the overload of Map that configures a derived type or by using an EntityTypeConfiguration for the derived type. The properties of an entity can be split between multiple tables using multiple Map calls. Calls to Map are additive, subsequent calls will not override configuration already performed via Map.
  8. MapToStoredProcedures(): It configures the entity type to use INSERT, UPDATE, and DELETE stored procedures.
  9. ToTable(): It configures the table name that the entity type is mapped to.
Property Configurations in Entity Framework:
  1. HasColumnAnnotation(): It sets an annotation in the model for the database column used to store the property.
  2. IsRequired(): It configures the property to be required. The database column used to store this property will be non-nullable. System.DateTime properties are required by default.
  3. IsConcurrencyToken(): It configures the property to be used as an optimistic concurrency token.
  4. IsRowVersion(): Configures the property to be a row version in the database.
  5. IsOptional(): It configures the property to be optional. The database column used to store this property will be nullable.
  6. HasParameterName(): It configures the name of the parameter used in the stored procedure for the property.
  7. HasDatabaseGeneratedOption(): It configures how values for the property are generated by the database, for example, computed, identity, or none.
  8. HasColumnOrder(): It configures the order of the database column used to store the property. This method is also used to specify key ordering when an entity type has a composite key.
  9. HasColumnType(): It configures the data type of the database column used to store the property.
  10. HasColumnName(): It configures the name of the database column used to store the property.
  11. HasMaxLength(int? value): It configures the property to have the specified maximum length. Here, the value parameter specifies the maximum length for the property. Setting ‘null’ will remove any maximum length restriction from the property and a default length will be used for the database column.
  12. HasPrecision(byte precision, byte scale): It configures the precision and scale of the property. Here, the precision parameter specifies the precision of the property and the scale parameter specifies the scale of the property.
  13. IsFixedLength(): It configures the property to be fixed length. Use HasMaxLength to set the length that the property is fixed to.
  14. IsVariableLength(): It configures the property to be variable length. String properties are variable length by default.

Note: In our next article, we will explain all the above Fluent API Configuration Methods with Examples using Entity Framework Code First Approach.

In the next article, I am going to discuss Entity Configurations using Entity Framework Fluent API with Examples. Here, in this article, I try to explain How to Configure Fluent API in Entity Framework Code First Approach with Examples. I hope you enjoyed this Fluent API configuration in the Entity Framework article. Please give your valuable feedback and suggestions about this article.

Leave a Reply

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