Fluent API in Entity Framework Core

Fluent API in Entity Framework Core

You can override the default Conventions in Entity Framework Core using Fluent API. By using it, you can configure many different things, as it provides more configuration options than Data Annotation Attributes. Also, Fluent API configurations have higher precedence than data annotation attributes.

Entity Framework Core Fluent API offers:

  • 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.

How to use Fluent API

Suppose I have a domain entity class named Country.

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

In order to use Fluent API, override the OnModelCreating() method of the Database Context class.

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 6 : I have set it’s PId property as primary key using the HasKey() function.
  • Line 12, 13 : I have 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.
  • Line 17, 18 : The AddedOn property is configured to be of date data type with default sql value given by getdate() method.
  • Line 20 : 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.

On doing the Entity Framework Core Migrations the Country table will be created on the database:

country table fluent api
Note: IsRequired() function is used to make a column ‘not null’ in the database.

Common Fluent API methods

Configurations Fluent API Methods Usage
Model Configurations HasDbFunction() Configures a database function
HasDefaultSchema() Specifies the database schema
HasSequence() Configures the database sequence
Entity Configuration HasIndex() Configures a property as Index
ToTable() Configures the name of the database table that the entity corresponds to.
HasKey() Configures a property as Primary Key
HasOne() Configures the One part of the relationship, for one-to-one or one-to-many relationships.
HasMany() Configure the many side of a one-to-many relationship.
WithOne() Configures the One part of the relationship, for one-to-one or one-to-many relationships.
WithMany() Configure the many side of a one-to-many relationship..
HasForeignKey() Configures the property as the foreign key
Ignore() Specifies the property should not be mapped to a database table
Property Configuration HasColumnName() Specifies the column name in the database for the property
HasColumnType() Specifies the data type of the column in the database for the property
HasDefaultValue() Specifies the default value of the column in the database for the property
HasDefaultValueSql() Specifies the default value expression of the column in the database for the property. Eg getdate()
HasMaxLength() Specifies the maximum length of the column in the database for the property
IsRequired() Specifies the database column should be not null.
IsUnicode() Specifies that the column should contain Unicode characters.
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.

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 Has & With methods must be combined to configure a valid relationship. The HasOne method along with the WithOne method is used to create Reference Navigation Properties. Similarly, the HasMany method along with the WithMethod method is used to create Collection Navigation Properties.

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

Download the source code.

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.