Introduction

If you develop with .NET, at some point you had to decide how your application would talk to the database. Write raw SQL? Use a micro ORM like Dapper? Or adopt a full ORM like Entity Framework Core? This decision goes far beyond performance β€” it directly affects the maintainability, the testability and, above all, the coupling of your application to the database.

In this article, I explore EF Core 8+ using Fluent API exclusively for entity mapping β€” never Data Annotations. I explain what an ORM is, compare the best-known ones on the market, show why EF Core offers a tactical and strategic advantage over micro ORMs like Dapper, and implement every possible relationship type with complete examples in C# 12. If you already work with EF Core and want to go deeper into advanced mapping, or if you are evaluating which data access strategy to adopt in your project, this guide is for you. To understand how EF Core behaves in high-load scenarios, also see Database Bottlenecks: Messaging and Pagination.

πŸ“¦ Source code: The complete implementation of this article is in the blog-zocateli-sample repository on GitHub. Clone it, explore it and adapt it to your context.


What an ORM Is and Which Ones Are Best Known

ORM (Object-Relational Mapping) is a technique that maps objects of your programming language to tables in a relational database. Instead of writing SQL by hand, you manipulate objects and the ORM takes care of translating those operations into SQL commands β€” INSERT, UPDATE, DELETE, SELECT β€” transparently.

The concept emerged to solve the so-called impedance mismatch: the fundamental difference between the object-oriented model (with inheritance, polymorphism, encapsulation) and the relational model (with tables, columns, foreign keys). An ORM bridges that gap automatically.

Full ORMs vs Micro ORMs

ORMs fall into two categories with very different philosophies:

TypeCharacteristicsExamples
Full ORMChange tracking, migrations, LINQ, lazy loading, automatic relationship mappingEF Core, Hibernate, NHibernate, SQLAlchemy, Django ORM
Micro ORMSimple query β†’ object mapping, no tracking, no migrations, manual SQLDapper, PetaPoco, Massive

Main ORMs on the Market

ORMLanguage/PlatformNote
Entity Framework CoreC# / .NETMicrosoft’s official ORM. Open source, cross-platform, supports multiple databases
HibernateJavaThe most mature ORM in the Java ecosystem. Inspiration for NHibernate
NHibernateC# / .NETPort of Hibernate to .NET. Robust, but with a more verbose API than EF Core
DapperC# / .NETMicro ORM created by Stack Overflow. Fast, lightweight, raw SQL
SQLAlchemyPythonThe most popular Python ORM. Supports Core (low level) and ORM (high level)
Django ORMPythonIntegrated into Django. Simplicity and productivity
ActiveRecordRubyIntegrated into Rails. Convention over configuration
SequelizeNode.jsORM for Node.js with support for PostgreSQL, MySQL, SQLite
PrismaNode.js / TypeScriptModern ORM with a declarative schema and type safety
TypeORMTypeScriptSupports decorators and Active Record/Data Mapper
GORMGoThe most popular ORM in the Go ecosystem

πŸ’‘ Tip: EF Core is the most widely used ORM in the .NET ecosystem and is actively maintained by Microsoft. In the Stack Overflow Developer Survey, it consistently appears among the most popular ORMs globally.


EF Core vs Mini ORMs: Beyond Performance

When people compare EF Core with Dapper, the conversation almost always revolves around performance: “Dapper is faster”. And it’s true β€” Dapper has less overhead because it is essentially a thin wrapper over ADO.NET. But focusing only on microseconds per query means losing sight of what really matters in a corporate software project.

What EF Core Offers That Dapper Doesn’t

FeatureEF CoreDapper
Change TrackingAutomatic β€” detects what changed and generates UPDATE only for the modified columnsManual β€” you write the full UPDATE
MigrationsBuilt-in database schema versioningNonexistent β€” you manage DDL by hand
LINQTyped queries checked at compile timeSQL as a string β€” errors only at runtime
Relationships.Include() / .ThenInclude() β€” automatic joinsYou write the JOIN and map it manually
Projections.Select(x => new { ... }) β€” generates optimized SQLYou write the projection in SQL
TransactionsSaveChanges() is transactional by defaultYou manage IDbTransaction manually
InterceptorsCross-cutting hooks (audit, soft delete, multi-tenancy)Nonexistent
Database abstractionSwitch providers without changing application codeRewrite EVERY SQL query

Total Decoupling: Tactical and Strategic Advantage

This is the most underestimated and most important point. With EF Core, your application doesn’t know SQL. It knows LINQ and entities. The EF Core provider translates LINQ into the database-specific SQL. This means that:

Tactical scenario (short term): Your company uses SQL Server in production. Licensing costs have grown. Management decides to migrate to PostgreSQL. With EF Core, you switch the provider (UseSqlServer β†’ UseNpgsql), adjust the migrations and you’re done. With Dapper, you rewrite hundreds or thousands of SQL queries that use SQL Server-specific syntax (TOP, NOLOCK, CROSS APPLY, etc.).

Strategic scenario (long term): The company is going to expand to multi-cloud. Some customers require Oracle, others PostgreSQL. With EF Core, the same application code runs on both β€” just configure the provider per tenant. With Dapper, you maintain two SQL codebases or use a limited subset of ANSI SQL that no database fully implements.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// The same application running on different databases β€” zero changes to business code
// Just switch the provider in Startup/Program.cs

// SQL Server
services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

// PostgreSQL
services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(connectionString));

// Oracle
services.AddDbContext<AppDbContext>(options =>
    options.UseOracle(connectionString));

// SQLite (for tests)
services.AddDbContext<AppDbContext>(options =>
    options.UseSqlite("Data Source=:memory:"));

ℹ️ Info: Database decoupling is not a technical luxury β€” it is a business decision. Companies that couple their application to the database’s SQL become hostages of licensing, vendor lock-in and migration costs. With EF Core, switching databases is a configuration decision, not a rewrite. To see how EF Core works with different databases in practice, check out REST API Pagination with C# and EF Core: Practical Guide.

EF Core abstraction diagram showing the C# application with LINQ connecting to PostgreSQL, SQL Server, Oracle and SQLite providers with no code changes


Why Fluent API and Never Data Annotations

EF Core offers two ways to configure the mapping between entities and tables: Data Annotations (attributes decorating the classes) and Fluent API (configuration in separate classes). This article uses Fluent API exclusively, and here is why:

Data Annotations β€” The Problem

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// ❌ DON'T DO THIS β€” Data Annotations pollute the domain
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Table("produtos")]
public class Produto
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [MaxLength(200)]
    [Column("nome_produto")]
    public string Nome { get; set; } = string.Empty;

    [Column(TypeName = "decimal(18,2)")]
    public decimal Preco { get; set; }
}

The problem is clear: your domain entity is contaminated with infrastructure details. The Produto class now depends on System.ComponentModel.DataAnnotations and System.ComponentModel.DataAnnotations.Schema β€” namespaces that are the responsibility of the data layer, not the domain. This violates the Separation of Concerns (SoC) principle and makes it impossible to have a truly independent Domain project.

Fluent API β€” The Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// βœ… Clean domain entity β€” no reference to EF Core at all
namespace MeuEcommerce.Domain.Entities;

public class Produto
{
    public int Id { get; private set; }
    public string Nome { get; private set; } = string.Empty;
    public decimal Preco { get; private set; }
    public bool Ativo { get; private set; } = true;
    public DateTime CriadoEm { get; private set; }

    public int CategoriaId { get; private set; }
    public Categoria Categoria { get; private set; } = null!;
    public ProdutoDetalhe? Detalhe { get; private set; }
    public ICollection<Tag> Tags { get; private set; } = [];
}

The configuration lives in a separate class, in the infrastructure project:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Infra.Data/Configurations/ProdutoConfiguration.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using MeuEcommerce.Domain.Entities;

namespace MeuEcommerce.Infra.Data.Configurations;

public class ProdutoConfiguration : IEntityTypeConfiguration<Produto>
{
    public void Configure(EntityTypeBuilder<Produto> builder)
    {
        builder.ToTable("produtos");

        builder.HasKey(p => p.Id);

        builder.Property(p => p.Nome)
            .HasMaxLength(200)
            .IsRequired();

        builder.Property(p => p.Preco)
            .HasColumnType("decimal(18,2)");

        builder.Property(p => p.Ativo)
            .HasDefaultValue(true);

        builder.Property(p => p.CriadoEm)
            .HasDefaultValueSql("NOW()");

        builder.HasIndex(p => p.Nome);
    }
}

⚠️ Warning: Data Annotations have real technical limitations: they don’t support configuring composite indexes, global filters, value converters, shadow properties, owned types and several other advanced features. Fluent API is the only way to access 100% of EF Core’s functionality.

Advantages of Fluent API

  1. Clean domain β€” entities are pure POCOs with no dependency on EF Core
  2. Separation of concerns β€” mapping lives in the infra project, not in the domain
  3. Full power β€” access to every EF Core feature
  4. Organization β€” one IEntityTypeConfiguration<T> class per entity
  5. Testability β€” entities can be instantiated without mocking EF Core
  6. Open/closed principle β€” adding configuration doesn’t change the entity

Configuring the DbContext

The DbContext is the central point of EF Core. It represents the session with the database and coordinates Change Tracking, queries and SaveChanges. With Fluent API, the DbContext automatically applies all configurations via ApplyConfigurationsFromAssembly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using Microsoft.EntityFrameworkCore;
using MeuEcommerce.Domain.Entities;

namespace MeuEcommerce.Infra.Data;

public class AppDbContext(DbContextOptions<AppDbContext> options)
    : DbContext(options)
{
    public DbSet<Produto> Produtos => Set<Produto>();
    public DbSet<Categoria> Categorias => Set<Categoria>();
    public DbSet<Tag> Tags => Set<Tag>();
    public DbSet<ProdutoDetalhe> ProdutoDetalhes => Set<ProdutoDetalhe>();
    public DbSet<Comentario> Comentarios => Set<Comentario>();
    public DbSet<Pagamento> Pagamentos => Set<Pagamento>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Applies ALL IEntityTypeConfiguration<T> in the assembly automatically
        // No need to register them one by one β€” add new classes and they are
        // discovered automatically via reflection
        modelBuilder.ApplyConfigurationsFromAssembly(
            typeof(AppDbContext).Assembly);
    }
}

πŸ’‘ Tip: Use the C# 12 primary constructor (public class AppDbContext(DbContextOptions<AppDbContext> options)) to simplify the constructor. And prefer DbSet<T> Produtos => Set<T>(); instead of DbSet<T> Produtos { get; set; } β€” it is cleaner and safer.


Every Relationship Type with Fluent API

I use an e-commerce domain to demonstrate every relationship type. First, the domain entities (Domain project β€” no reference to EF Core):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
namespace MeuEcommerce.Domain.Entities;

public class Categoria
{
    public int Id { get; private set; }
    public string Nome { get; private set; } = string.Empty;
    public string? Descricao { get; private set; }
    public bool Ativa { get; private set; } = true;
    public DateTime CriadoEm { get; private set; }
    public ICollection<Produto> Produtos { get; private set; } = [];
}

public class Tag
{
    public int Id { get; private set; }
    public string Nome { get; private set; } = string.Empty;
    public ICollection<Produto> Produtos { get; private set; } = [];
}

public class ProdutoDetalhe
{
    public int Id { get; private set; }
    public string DescricaoCompleta { get; private set; } = string.Empty;
    public string? Especificacoes { get; private set; }
    public double PesoKg { get; private set; }
    public int ProdutoId { get; private set; }
    public Produto Produto { get; private set; } = null!;
}

public class Comentario
{
    public int Id { get; private set; }
    public string Texto { get; private set; } = string.Empty;
    public DateTime CriadoEm { get; private set; }
    public int ProdutoId { get; private set; }
    public Produto Produto { get; private set; } = null!;

    // Self-referencing (reply to another comment)
    public int? ComentarioPaiId { get; private set; }
    public Comentario? ComentarioPai { get; private set; }
    public ICollection<Comentario> Respostas { get; private set; } = [];
}

One-to-Many Relationship (1:N)

The most common relationship. A Categoria has many Produtos:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class CategoriaConfiguration : IEntityTypeConfiguration<Categoria>
{
    public void Configure(EntityTypeBuilder<Categoria> builder)
    {
        builder.ToTable("categorias");
        builder.HasKey(c => c.Id);

        builder.Property(c => c.Nome)
            .HasMaxLength(100)
            .IsRequired();

        builder.Property(c => c.Descricao)
            .HasMaxLength(500);

        builder.Property(c => c.Ativa)
            .HasDefaultValue(true);

        builder.Property(c => c.CriadoEm)
            .HasDefaultValueSql("NOW()");

        builder.HasIndex(c => c.Nome)
            .IsUnique();

        // 1:N β€” One Categoria has many Produtos
        builder.HasMany(c => c.Produtos)
            .WithOne(p => p.Categoria)
            .HasForeignKey(p => p.CategoriaId)
            .OnDelete(DeleteBehavior.Restrict); // Prevents deleting a category that has products
    }
}

One-to-One Relationship (1:1)

A Produto has one ProdutoDetalhe (and vice versa):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class ProdutoDetalheConfiguration : IEntityTypeConfiguration<ProdutoDetalhe>
{
    public void Configure(EntityTypeBuilder<ProdutoDetalhe> builder)
    {
        builder.ToTable("produto_detalhes");
        builder.HasKey(d => d.Id);

        builder.Property(d => d.DescricaoCompleta)
            .HasMaxLength(4000)
            .IsRequired();

        builder.Property(d => d.Especificacoes)
            .HasColumnType("text");

        builder.Property(d => d.PesoKg)
            .HasColumnType("double precision");

        // 1:1 β€” A ProdutoDetalhe belongs to exactly one Produto
        builder.HasOne(d => d.Produto)
            .WithOne(p => p.Detalhe)
            .HasForeignKey<ProdutoDetalhe>(d => d.ProdutoId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasIndex(d => d.ProdutoId)
            .IsUnique(); // Ensures each product has at most 1 detail
    }
}

Many-to-Many Relationship (N:N)

A Produto can have several Tags, and a Tag can be on several Produtos. Since EF Core 5, N:N works without an explicit join table. In EF Core 8+, you can configure it via Fluent API to have full control:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class ProdutoConfiguration : IEntityTypeConfiguration<Produto>
{
    public void Configure(EntityTypeBuilder<Produto> builder)
    {
        builder.ToTable("produtos");
        builder.HasKey(p => p.Id);

        builder.Property(p => p.Nome)
            .HasMaxLength(200)
            .IsRequired();

        builder.Property(p => p.Sku)
            .HasMaxLength(50)
            .IsRequired();

        builder.Property(p => p.Preco)
            .HasColumnType("decimal(18,2)");

        builder.Property(p => p.Ativo)
            .HasDefaultValue(true);

        builder.Property(p => p.CriadoEm)
            .HasDefaultValueSql("NOW()");

        builder.HasIndex(p => p.Sku)
            .IsUnique();

        // N:N β€” Produto ↔ Tag (join table configured by EF Core)
        builder.HasMany(p => p.Tags)
            .WithMany(t => t.Produtos)
            .UsingEntity<Dictionary<string, object>>(
                "produto_tags", // Join table name
                right => right.HasOne<Tag>()
                    .WithMany()
                    .HasForeignKey("TagId")
                    .OnDelete(DeleteBehavior.Cascade),
                left => left.HasOne<Produto>()
                    .WithMany()
                    .HasForeignKey("ProdutoId")
                    .OnDelete(DeleteBehavior.Cascade),
                join =>
                {
                    join.HasKey("ProdutoId", "TagId");
                    join.ToTable("produto_tags");
                });
    }
}

πŸ’‘ Tip: If you need additional properties in the join table (such as DataAssociacao), create an explicit entity instead of using Dictionary<string, object>. EF Core 8+ supports this natively with UsingEntity<ProdutoTag>().

Self-Referencing

A Comentario can be a reply to another Comentario β€” it is a 1:N relationship with itself:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class ComentarioConfiguration : IEntityTypeConfiguration<Comentario>
{
    public void Configure(EntityTypeBuilder<Comentario> builder)
    {
        builder.ToTable("comentarios");
        builder.HasKey(c => c.Id);

        builder.Property(c => c.Texto)
            .HasMaxLength(2000)
            .IsRequired();

        builder.Property(c => c.CriadoEm)
            .HasDefaultValueSql("NOW()");

        // 1:N with Produto
        builder.HasOne(c => c.Produto)
            .WithMany()
            .HasForeignKey(c => c.ProdutoId)
            .OnDelete(DeleteBehavior.Cascade);

        // Self-referencing β€” a Comentario can have replies
        builder.HasOne(c => c.ComentarioPai)
            .WithMany(c => c.Respostas)
            .HasForeignKey(c => c.ComentarioPaiId)
            .OnDelete(DeleteBehavior.Restrict) // No cascade delete (keeps replies)
            .IsRequired(false); // Nullable FK β€” root comments have no parent

        builder.HasIndex(c => c.ProdutoId);
        builder.HasIndex(c => c.ComentarioPaiId);
    }
}

Inheritance in EF Core 8+: TPH, TPT and TPC

EF Core supports three strategies to map inheritance hierarchies to tables:

Domain Entities (Inheritance)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
namespace MeuEcommerce.Domain.Entities;

public abstract class Pagamento
{
    public int Id { get; private set; }
    public decimal Valor { get; private set; }
    public DateTime PagoEm { get; private set; }
    public int PedidoId { get; private set; }
}

public class PagamentoCartao : Pagamento
{
    public string UltimosDigitos { get; private set; } = string.Empty;
    public string Bandeira { get; private set; } = string.Empty;
    public int Parcelas { get; private set; }
}

public class PagamentoPix : Pagamento
{
    public string ChavePix { get; private set; } = string.Empty;
    public string TransacaoId { get; private set; } = string.Empty;
}

public class PagamentoBoleto : Pagamento
{
    public string CodigoBarras { get; private set; } = string.Empty;
    public DateTime Vencimento { get; private set; }
}

Table Per Hierarchy (TPH) β€” One Table for the Whole Hierarchy

All classes in the same table. EF Core uses a discriminator column to know which type each row is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class PagamentoTphConfiguration : IEntityTypeConfiguration<Pagamento>
{
    public void Configure(EntityTypeBuilder<Pagamento> builder)
    {
        builder.ToTable("pagamentos");
        builder.HasKey(p => p.Id);

        // TPH β€” Discriminator defines the concrete type
        builder.HasDiscriminator<string>("tipo_pagamento")
            .HasValue<PagamentoCartao>("cartao")
            .HasValue<PagamentoPix>("pix")
            .HasValue<PagamentoBoleto>("boleto");

        builder.Property(p => p.Valor)
            .HasColumnType("decimal(18,2)");

        builder.Property(p => p.PagoEm)
            .HasDefaultValueSql("NOW()");
    }
}

Table Per Type (TPT) β€” One Table per Class

Each class has its own table. The base table contains the common properties, and each derived table contains only the specific properties + an FK to the base table:

1
2
3
4
5
6
// TPT β€” Each type has its own table with an FK to pagamentos
builder.ToTable("pagamentos"); // Base table

builder.Entity<PagamentoCartao>().ToTable("pagamentos_cartao");
builder.Entity<PagamentoPix>().ToTable("pagamentos_pix");
builder.Entity<PagamentoBoleto>().ToTable("pagamentos_boleto");

Table Per Concrete Type (TPC) β€” EF Core 7+

Each concrete class has its own complete table (no base table). Each table contains all the columns β€” both from the base and from the derived class:

1
2
3
4
5
6
// TPC β€” Each concrete class is an independent table (EF Core 7+)
builder.UseTpcMappingStrategy();

builder.Entity<PagamentoCartao>().ToTable("pagamentos_cartao");
builder.Entity<PagamentoPix>().ToTable("pagamentos_pix");
builder.Entity<PagamentoBoleto>().ToTable("pagamentos_boleto");
StrategyProsConsWhen to use
TPHPerformance (1 table, no JOINs)Nullable columns for derived typesFew types, frequent access
TPTNormalized schemaJOIN for every query + worse performanceA clean schema matters more than performance
TPCNo JOINs, no nullable columnsColumns duplicated across tables, UNION for polymorphic queriesTypes rarely queried together

⚠️ Warning: For most scenarios, TPH is the choice recommended by Microsoft and the community. TPT has known performance problems because it requires JOINs in every query. TPC (EF Core 7+) is useful when each concrete type is queried independently.


Advanced Features of EF Core 8+

Value Converters

They let you transform values between C# and the database. Useful for persisting enums as strings, encrypting fields or converting complex types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Convert enum to string in the database
public enum StatusPedido
{
    Pendente,
    Aprovado,
    Enviado,
    Entregue,
    Cancelado
}

// In the Fluent API configuration:
builder.Property(p => p.Status)
    .HasConversion<string>() // Persists the enum as a string ("Pendente", "Aprovado", etc.)
    .HasMaxLength(20);

// Or with a custom converter:
builder.Property(p => p.Status)
    .HasConversion(
        v => v.ToString().ToLowerInvariant(),
        v => Enum.Parse<StatusPedido>(v, ignoreCase: true));

Global Query Filters

They automatically apply filters to every query of an entity. Ideal for soft delete and multi-tenancy:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class ProdutoConfiguration : IEntityTypeConfiguration<Produto>
{
    public void Configure(EntityTypeBuilder<Produto> builder)
    {
        // Global filter β€” queries NEVER return inactive products
        // SELECT * FROM produtos WHERE ativo = true (automatic on every query)
        builder.HasQueryFilter(p => p.Ativo);
    }
}

// To ignore the filter when needed (e.g., admin panel):
var todosProdutos = await context.Produtos
    .IgnoreQueryFilters()
    .ToListAsync();

JSON Columns (EF Core 7+)

EF Core 7+ lets you map complex objects as JSON columns in the database. Ideal for semi-structured data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Entity with a complex property
public class Produto
{
    public int Id { get; private set; }
    public string Nome { get; private set; } = string.Empty;
    public Dimensoes Dimensoes { get; private set; } = new();
}

public class Dimensoes
{
    public double Largura { get; set; }
    public double Altura { get; set; }
    public double Profundidade { get; set; }
    public string Unidade { get; set; } = "cm";
}

// Fluent API mapping β€” Dimensoes as a JSON column
builder.OwnsOne(p => p.Dimensoes, dim =>
{
    dim.ToJson(); // Stores as JSON in the database
});

Primitive Type Collections (EF Core 8+)

EF Core 8 introduced native support for collections of primitive types β€” with no need for a separate table or a Value Converter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Produto
{
    public int Id { get; private set; }
    public string Nome { get; private set; } = string.Empty;
    public List<string> ImagensUrls { get; private set; } = [];
    public List<string> PalavrasChave { get; private set; } = [];
}

// Mapping β€” stored as a JSON array in the database
builder.Property(p => p.ImagensUrls)
    .HasColumnType("jsonb"); // PostgreSQL β€” or 'nvarchar(max)' for SQL Server

builder.Property(p => p.PalavrasChave)
    .HasColumnType("jsonb");

ℹ️ Info: EF Core 8+ primitive type collections are stored as native JSON arrays. On PostgreSQL, use jsonb for efficient indexing. On SQL Server, EF Core automatically serializes to nvarchar(max).


Tips and Good Practices

  1. One IEntityTypeConfiguration<T> per entity β€” never configure multiple entities in OnModelCreating. Use ApplyConfigurationsFromAssembly() for automatic discovery.

  2. Always configure OnDelete explicitly β€” the default behavior varies across providers. Be explicit with DeleteBehavior.Restrict, .Cascade or .SetNull to avoid surprises.

  3. Use private set; in entities β€” protect the internal state. Domain entities should be modified only by business methods, not by public setters.

  4. Configure indexes for FKs and search columns β€” EF Core does NOT automatically create indexes for foreign keys in every provider. Use builder.HasIndex(p => p.CategoriaId).

  5. Prefer AsNoTracking() for read queries β€” if you are not going to modify the data, disable Change Tracking for a significant performance gain.

  6. Never expose the DbContext directly in the API β€” use the Repository pattern or intermediate services. The DbContext is infrastructure.

  7. Always set HasMaxLength() β€” without HasMaxLength, EF Core creates nvarchar(max) / text columns, which hurt performance and prevent indexing.

  8. Configure HasDefaultValueSql() for date columns β€” use database expressions (NOW(), GETUTCDATE()) so dates are generated by the server, not by the application.


Conclusion

Entity Framework Core 8+ with Fluent API offers much more than simple object-relational mapping. It delivers total decoupling from the database β€” an advantage that transcends the technical and directly impacts the business. While micro ORMs like Dapper tie you to vendor-specific SQL, EF Core lets your application speak LINQ and leaves the provider to translate it into the database’s dialect.

By using Fluent API exclusively with IEntityTypeConfiguration<T>, your domain entities stay clean, testable and free of any infrastructure dependency. The relationships (1:1, 1:N, N:N, self-referencing), the inheritance strategies (TPH, TPT, TPC) and the advanced features (Value Converters, Global Query Filters, JSON columns, primitive collections) make EF Core a complete tool for any data access scenario.

To go deeper into managing Migrations in multi-layer projects with dotnet secrets and scaffolding of existing databases, check out the dedicated article EF Core Migrations: Multi-Project, Secrets and Scaffolding. And if performance is your concern, see how EF Core behaves in high-load scenarios in Database Bottlenecks: Messaging and Pagination.


Read Also


References