Fluent API in Entity Framework Core

Fluent API in Entity Framework Core

You can override the default conventions of 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 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 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:

  • I have set its PId property as primary key using the HasKey() function.
  • I have configured its 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 AddedOn property is configured to be of date data type with default sql value given by getdate() method.
  • 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 migration 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()td>

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() Configures the Many part of the relationship, for one-to-Many or many-to-many relationships.
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.

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

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