In this lesson, you will learn how to improve performance and memory efficiency by mapping a single C# class to two or more database tables using Entity Splitting.
The Concept
Sometimes, your application has a "heavy" entity—a class with many properties where some are used constantly (like a user's Username and Email) and others are rarely accessed (like a large Biography or ProfileBlob). If you pull the entire entity every time you run a query, you waste I/O resources and memory loading data you don't need.
Entity Splitting allows you to keep your clean, singular domain model in C# while physically partitioning the data into multiple tables in SQL Server. EF Core handles the JOIN logic behind the scenes, so your code remains simple.
Implementation
To implement this, you use the Fluent API in your OnModelCreating method to specify which properties belong to which table. Both tables must share the same primary key to maintain the relationship.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
// Map common fields to the main table
entity.ToTable("Users");
// Map heavy fields to a secondary table
entity.SplitToTable("UserProfiles", tableBuilder =>
{
tableBuilder.Property(u => u.Id).HasColumnName("UserId");
tableBuilder.Property(u => u.Biography);
tableBuilder.Property(u => u.ProfileBlob);
});
});
}
Why Do This?
By splitting the entity, EF Core can generate queries that only hit the Users table when you don't need the profile details. This reduces the width of the rows returned, decreases the memory footprint of the loaded entities, and can significantly speed up your most common read operations.
It is important to remember that when you do access the heavy properties, EF Core will perform an internal JOIN to fetch the data from the secondary table. Use this technique strategically for entities that are frequently queried but contain "bloated" data that isn't required for every use case.
Key Takeaway: Entity Splitting lets you map one class to multiple tables, enabling you to optimize memory usage and query performance by isolating rarely-used, high-volume properties into secondary tables.