In this lesson, you will learn how to explicitly map your C# classes to specific database tables and schemas to align your application with existing infrastructure.
By default, EF Core follows naming conventions (like pluralizing your class names) to determine table names. However, when working with legacy databases or strict corporate naming standards, your class names rarely match the database schema exactly.
Mapping Tables and Schemas
You can override these defaults using the Fluent API inside your DbContext class by overriding the OnModelCreating method. This gives you complete control over where EF Core looks for your data.
Consider a scenario where your User entity needs to map to a table named AspNetUsers inside a schema named Identity:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.ToTable("AspNetUsers", schema: "Identity");
}
Why Use Explicit Mapping?
- Legacy Integration: You often cannot change the database structure to suit your code; you must change the code to suit the database.
- Multi-tenancy: In some architectures, you might place different entities into separate schemas to enforce security boundaries at the database level.
- Clean Domain Models: You can keep your C# classes named descriptively (e.g.,
Product) while mapping them to obscure legacy table names (e.g.,tbl_prd_01_final) without polluting your domain logic.
If you don't provide a schema name, EF Core defaults to the database's default schema (usually dbo in SQL Server). If you find your application is throwing "Table not found" exceptions, it is almost always because the ToTable configuration does not match the exact naming and schema requirements of your database provider.
You can also combine this with other configurations. For example, if you wanted to map a property to a specific column name while keeping the table mapping, you simply chain the methods together, keeping your configuration centralized and readable.
Key Takeaway: Use the ToTable() method within OnModelCreating to decouple your domain entity names from your physical database table names and schemas.