Entity Framework Core: Fluent API

Md Asif AlamMd Asif Alam
3 min read

Here are notes explaining Entity Framework Core (EF Core) Fluent API based on the provided code:

EF Core Fluent API Notes

Overview

  • Fluent API provides a way to configure domain classes for the database schema and relationships.

  • It offers more control and flexibility than Data Annotations.

  • Fluent API configurations are usually done by implementing IEntityTypeConfiguration for each entity.

Entity Configuration Example

  • For each entity, create a configuration class implementing IEntityTypeConfiguration.

  • Implement the Configure method where you configure properties, keys, relationships, and other aspects.

Key Configuration Topics

1. Property Configuration

  • Use Property() to configure entity properties.

  • Example configurations:

    • HasMaxLength(50) limits string length to 50 characters.

    • IsRequired() enforces non-nullability.

    • HasColumnName("ColumnName") customizes column names.

    • Ignore() excludes a property from mapping.

Example:

modelBuilder.Property(u => u.FirstName).HasMaxLength(50);
modelBuilder.Property(u => u.FirstName).IsRequired();
modelBuilder.Ignore(u => u.FullName);

2. Primary Key Configuration

  • Use HasKey() to specify primary key(s).

  • Composite keys are created by passing multiple key properties as anonymous type.

Example:

modelBuilder.HasKey(u => u.Author_Id);
modelBuilder.HasKey(u => new { u.Author_Id, u.Book_Id }); // Composite key

3. Table Name Customization

  • Use ToTable("TableName") to map an entity to a different table name.

Example:

modelBuilder.ToTable("Fluent_BookDetails");

4. Relationships Configuration

  • One-to-Many: Use HasOne().WithMany().HasForeignKey() to configure one-to-many relationships.

Example:

modelBuilder.HasOne(u => u.Publisher).WithMany(u => u.Books)
    .HasForeignKey(u => u.Publisher_Id);
  • Many-to-Many with join entity: Use composite key on join entity and configure two one-to-many relationships.

Example:

modelBuilder.HasKey(u => new { u.Author_Id, u.Book_Id });
modelBuilder.HasOne(u => u.Book).WithMany(u => u.BookAuthorMap)
    .HasForeignKey(u => u.Book_Id);
modelBuilder.HasOne(u => u.Author).WithMany(u => u.BookAuthorMap)
    .HasForeignKey(u => u.Author_Id);
  • One-to-One: Use HasOne().WithOne().HasForeignKey() for one-to-one relationships.

Example:

modelBuilder.HasOne(b => b.Book).WithOne(b => b.BookDetail)
    .HasForeignKey(u => u.Book_Id);

Summary of Configurations for Each Entity

EntityKeyProperty ConfigurationsRelationshipsOther Notes
Fluent_AuthorAuthor_IdFirstName: max length 50, required; LastName: required; Ignore FullNameNavigation via BookAuthorMap join entityFullName is [NotMapped]
Fluent_BookBookIdISBN: max length 50, required; Ignore PriceRangeOne-to-many with Publisher; Navigation via BookAuthorMapPriceRange is [NotMapped]
Fluent_BookAuthorMapComposite (Author_Id, Book_Id)Composite primary key on Author_Id + Book_IdMany-to-many mapping between Books and AuthorsJoin entity for many-to-many
Fluent_BookDetailBookDetail_IdNumberOfChapters (column: NoOfChapters), requiredOne-to-one with BookTable name customized
Fluent_PublisherPublisher_IdName: requiredOne-to-many with Books

How to Apply Configurations

In your DbContext's OnModelCreating method, apply configurations like this:

modelBuilder.ApplyConfiguration(new FluentAuthorConfig());
modelBuilder.ApplyConfiguration(new FluentBookAuthorMapConfig());
modelBuilder.ApplyConfiguration(new FluentBookConfig());
modelBuilder.ApplyConfiguration(new FluentBookDetailConfig());
modelBuilder.ApplyConfiguration(new FluentPublisherConfig());

Additional Notes

  • Properties decorated with [NotMapped] are ignored in Fluent configuration with Ignore().

  • Composite keys require explicitly declaring all key properties with HasKey().

  • Fluent API allows configuring foreign key names and navigation properties explicitly.

  • Custom table and column names improve control over the database schema.

These notes summarize the core concepts demonstrated in your EF Core Fluent API configuration code. They provide a good foundation for understanding how to map your domain models to the database schema effectively.

0
Subscribe to my newsletter

Read articles from Md Asif Alam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Md Asif Alam
Md Asif Alam

๐Ÿš€ Full Stack .NET Developer & React Enthusiast ๐Ÿ‘จโ€๐Ÿ’ป About Me: With 3+ years of experience, I'm passionate about crafting robust solutions and seamless user experiences through code. ๐Ÿ’ผ Expertise: Proficient in .NET Core API, ASP.NET MVC, React.js, and SQL. Skilled in backend architecture, RESTful APIs, and frontend development. ๐ŸŒŸ Achievements: Led projects enhancing scalability by 50%, delivered ahead of schedule, and contributed to open-source initiatives. ๐Ÿ” Future Focus: Eager to embrace new technologies and drive innovation in software development. ๐Ÿ“ซ Let's Connect: Open to new opportunities and collaborations. Reach me on LinkedIn or GitHub!