Fluent API in Entity Framework Core

Fluent API in Entity Framework Core

Entity Framework Core Fluent API is used to build model based on entity classes. We can also override the default Conventions of Entity Framework Core using Fluent API when targetting the database schema as Fluent API has higher precedence than conventions and data annotations.

Entity Framework Core Fluent API offers the following features.

  • Model Configuration: Configures an EF model to database mappings.
  • Entity Configuration: Configures PrimaryKey, AlternateKey, Index, table name, one-to-one, one-to-many, many-to-many relationships etc.
  • Property Configuration: Configures property to column mapping e.g. column name, default value, nullability, Foreignkey, data type, etc.

Entity Framework Core Fluent API Example

Suppose we have am entity class named Country as shown below.

public class Country
{
    public int PId { get; set; }
 
    public string Name { get; set; }
 
    public DateTime AddedOn { get; set; }
}

We write Entity Framework Core Fluent API Configurations inside the OnModelCreating() method of the Database Context (DbContext) of the app.

public class CountryContext : DbContext
{
    public CompanyContext(DbContextOptions<CompanyContext> options) : base(options)
    {
    }

    public DbSet<Country> Country { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here
 
        //Entity Configuration
        modelBuilder.Entity<Country>().HasKey(s => s.PId);
 
        //Property Configurations
        modelBuilder.Entity<Country>(entity =>
        {
            entity.Property(e => e.Name)
                  .HasColumnName("CountryName")
                  .HasDefaultValue("USA")
                  .IsRequired();
 
            entity.Property(e => e.AddedOn)
                  .HasColumnType("date")
                  .HasDefaultValueSql("(getdate())");
        });
        modelBuilder.Entity<Country>().Ignore(e => e.population); 
    }
}

In the above code the Country entity is configured in the following manner:

  • Line 14 : set it’s PId property as primary key using the HasKey() function.
  • Line 19-22 : configured it’s Name property to be set as CountryName on the database table, and it should be a not null column with default value as USA. The IsRequired() method is used to make a column ‘not null’ in the database.
  • Line 25, 26 : The AddedOn property is configured to be of date data type with default sql value given by getdate() method.
  • Line 28 : The Population will not be mapped to the database table i.e. its column will not be created. The Ignore() method has done this configuration here.
Note: If you have more entities then you have to write their configuations in the same OnModelCreating method.

On doing the Entity Framework Core Migrations the Country table will be created on the database which is shown in the below image.

entity framework core fluent api

Fluent API Methods

In the below table we have listed down some of the most common methods of Entity Framework Core Fluent API.

Configuration Type Fluent API Methods Usage
Model Configuration HasDbFunction() Configures a database function
Model Configuration HasDefaultSchema() Specifies the database schema
Model Configuration HasSequence() Configures the database sequence
Entity Configuration HasIndex() Configures a property as Index
Entity Configuration ToTable() Configures the name of the database table that the entity corresponds to.
Entity Configuration HasKey() Configures a property as Primary Key
Entity Configuration HasNoKey() Tells that the entity cannot have a key. Such entities are never tracked for changes and therefore are never inserted, updated or deleted on the database.
Entity Configuration HasOne() Configures the One part of the relationship, for one-to-one or one-to-many relationships.
Entity Configuration HasMany() Configure the many side of a one-to-many relationship.
Entity Configuration WithOne() Configures the One part of the relationship, for one-to-one or one-to-many relationships.
Entity Configuration WithMany() Configure the many side of a one-to-many relationship..
Entity Configuration HasForeignKey() Configures the property as the foreign key
Entity Configuration Ignore() Specifies the property should not be mapped to a database table
Entity Configuration HasConstraintName() Specifies name of the foreign key constraint for a relationship
Property Configuration HasColumnName() Specifies the column name in the database for the property
Property Configuration HasColumnType() Specifies the data type of the column in the database for the property
Property Configuration HasDefaultValue() Specifies the default value of the column in the database for the property
Property Configuration HasDefaultValueSql() Specifies the default value expression of the column in the database for the property. Eg getdate()
Property Configuration HasMaxLength() Specifies the maximum length of the column in the database for the property
Property Configuration IsRequired() Specifies the database column should be not null
Property Configuration IsUnicode() Specifies that the column should contain Unicode characters
Property Configuration ValueGeneratedOnAdd() Configures that the property has a generated value when saving a new entity

“Has/With” Pattern for Configuring Relationships

The Has/With pattern is widely used when configuring relationships with the Fluent API. The Has & With methods must be combined to configure a valid relationship.

There are 2 variants of Has method, these are:

  • 1. HasOne
  • 2. HasMany

Similarly, there are 2 variants of With method, these are:

  • 1. WithOne
  • 2. WithMany

The HasOne method along with the WithOne method is used to create Reference Navigation Properties. Similarly, the HasMany method along with the WithMany method is used to create Collection Navigation Properties.

You will learn the usage of these methods in the below 3 tutorials.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate