Introduction
One of the most misleading situations in Entity Framework Core is finding a navigation property with a null value even though the relationship is clearly defined in the entity model. Developers often conclude that the relationship mapping is incorrect. In reality, defining a relationship does not mean that related data will automatically be loaded in every query.
This lesson separates two different concerns: how the relationship is configured in the database model and how related rows are loaded when a query executes. We will compare flawed code that relies on lazy loading with explicit eager loading through Include and a projection-based approach that returns only the fields required by the application.
The example uses a One-to-Many relationship in which a Department has many Employee records. The same principles apply to relationships such as Order-OrderItem, Blog-Post and Category-Product.
1. Relationship configuration is not data loading
The following entity classes describe a One-to-Many relationship:
public class Department
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public ICollection<Employee> Employees { get; set; } = new List<Employee>();
}
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; } = string.Empty;
public int DepartmentId { get; set; }
public Department? Department { get; set; }
}Department.Employees represents the employees belonging to a department, while Employee.Department represents the department associated with an employee. Defining these navigation properties tells EF Core about the relationship. It does not instruct EF Core to retrieve employees whenever a department is queried.
For example, this query retrieves departments only:
var departments = await dbContext.Departments
.ToListAsync();After this query, an empty Department.Employees collection does not prove that the relationship is broken. The related rows may simply not have been requested. Initializing the collection prevents many null collection problems, but it does not load database data. Keep these cases separate:
- Empty collection: no related rows exist or the related rows were not loaded.
- Null reference navigation: the related entity was not loaded, the relationship is optional, or no matching row exists.
2. Configuring the relationship explicitly
Conventions handle many simple relationships correctly. Explicit configuration is useful when there are multiple foreign keys, optional relationships, custom table mappings or domain rules that should be made clear.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>()
.HasMany(department => department.Employees)
.WithOne(employee => employee.Department)
.HasForeignKey(employee => employee.DepartmentId)
.IsRequired();
}This configuration tells EF Core that every employee must belong to a department and that DepartmentId is the foreign key. It affects the EF Core model and database relationship, but it does not automatically add an Include to every query.
Consider the following query:
var employee = await dbContext.Employees
.FirstOrDefaultAsync(employee => employee.Id == employeeId);
Console.WriteLine(employee?.Department?.Name);Department can still be null because the related department was not loaded. That result does not, by itself, demonstrate a mapping error.
3. The flawed approach: relying on lazy loading
When lazy loading is enabled, accessing a navigation property can cause EF Core to send another database query. Proxy-based lazy loading requires the appropriate package and configuration:
optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(connectionString);In common proxy scenarios, navigation properties also need to be virtual:
public virtual ICollection<Employee> Employees { get; set; } = new List<Employee>();
public virtual Department? Department { get; set; }The main problem is that the database operation becomes invisible in the calling code:
var departments = await dbContext.Departments
.ToListAsync();
foreach (var department in departments)
{
foreach (var employee in department.Employees)
{
Console.WriteLine($"{department.Name}: {employee.FullName}");
}
}The first query loads the departments, and accessing Employees may send one additional query for each department. This is the N+1 Query problem: one query loads the parent rows and N additional queries load the related rows. It can become expensive when network latency or the number of departments increases.
Lazy loading may also fail to behave as expected in several situations:
- The lazy-loading proxy package was not installed or enabled.
- The navigation property is not
virtualin a proxy-based configuration. - The entity is accessed after the context has been disposed.
- Serialization occurs after the context lifetime has ended.
- A projection returned a DTO or anonymous object rather than an entity with usable navigation properties.
For these reasons, lazy loading should be evaluated carefully, especially in web APIs and high-traffic applications. It is convenient, but it can hide database roundtrips and create serious performance problems.
4. Explicit eager loading with Include
When the related data is known in advance, express that requirement directly in the query by using eager loading:
var departments = await dbContext.Departments
.Include(department => department.Employees)
.ToListAsync();The intent is now visible in the query. Reading the employees does not depend on a hidden lazy-loading operation:
var department = await dbContext.Departments
.Include(department => department.Employees)
.SingleOrDefaultAsync(department => department.Id == departmentId);
if (department is null)
{
return;
}
foreach (var employee in department.Employees)
{
Console.WriteLine(employee.FullName);
}Use ThenInclude when the query must continue through another navigation property. For example, if every employee has a related position:
var departments = await dbContext.Departments
.Include(department => department.Employees)
.ThenInclude(employee => employee.Position)
.ToListAsync();Do not automatically include every possible relationship. Loading several collection navigations in one query can produce large joins, repeated columns and excessive memory usage. Depending on the result shape, filtered include, split queries or projection may be more appropriate.
5. Projection: load only what the application needs
A page or API endpoint rarely needs the complete entity graph. If the application only displays the department name and employee names, a DTO projection provides better control:
public sealed class DepartmentSummaryDto
{
public int Id { get; init; }
public string Name { get; init; } = string.Empty;
public List<string> EmployeeNames { get; init; } = new();
}var result = await dbContext.Departments
.Select(department => new DepartmentSummaryDto
{
Id = department.Id,
Name = department.Name,
EmployeeNames = department.Employees
.Select(employee => employee.FullName)
.ToList()
})
.ToListAsync();EF Core attempts to translate the projection into SQL and retrieve only the required columns. The query does not need to materialize every entity property, populate a full change-tracking graph or expose unused relationships. Projection is especially useful for read-only pages and API response models.
There is an important limitation: the result is a DTO or anonymous object, not a normal tracked entity. Do not expect to modify it and call SaveChangesAsync as if it were an entity instance. For updates, query the appropriate entity, choose the tracking strategy deliberately, or attach a controlled entity instance with explicitly marked properties.
6. A systematic diagnostic process
- Verify the database relationship. The employee's
DepartmentIdshould point to an existing department, and the foreign key constraint should be valid. - Check whether the query loads related data. Look for
Include, explicit loading or a correctly configured lazy-loading mechanism. - Inspect the generated SQL. Use
ToQueryString()to see whether the query contains the expected join or related-data operation.
var query = dbContext.Departments
.Include(department => department.Employees)
.Where(department => department.Id == departmentId);
Console.WriteLine(query.ToQueryString());- Check for projection. If
Selectreturns only selected fields, do not expect an entity navigation property to be populated automatically. - Check the context lifetime. Accessing a navigation after the context has been disposed can fail in lazy-loading scenarios.
- Distinguish reference and collection navigations. An optional reference navigation can legitimately be
nullwhen no related row exists. A collection navigation should normally be an empty collection rather thannull.
7. Common mistakes
- Assuming that declaring a navigation property automatically loads related rows.
- Enabling lazy loading everywhere without monitoring the number of SQL commands.
- Loading the entire entity graph with multiple
Includecalls for a simple list screen. - Treating a projection result as a tracked entity and attempting to update it directly.
- Creating a new migration immediately when a navigation property is null. First inspect the query and loading strategy.
- Failing to verify that the foreign key value points to an existing principal row.
8. Short practice exercise
Complete the following exercise:
- Create the
DepartmentandEmployeeentities. - Add seed data for one department and at least three employees.
- First run only
Departments.ToListAsync()and try to read the employees. - Add
Include(department => department.Employees)and compare the result. - Enable lazy loading, inspect SQL logging and count the generated queries.
- Finally, create a DTO projection containing the department name and employee names.
When you finish, you should be able to answer these questions: Does a null navigation property prove that the relationship mapping is wrong? How many roundtrips does each loading strategy create? Why can a projection be better than returning entities from an API?
Conclusion
A null or empty navigation property does not automatically mean that the EF Core relationship is incorrectly configured. Relationship configuration describes how tables and foreign keys are connected; loading related data is a separate query decision.
When the required related data is known in advance, Include provides an explicit and readable eager-loading strategy. When a read-only screen or API needs only a few fields, projection reduces the amount of data transferred and gives the response model better boundaries. Lazy loading can be useful in limited scenarios, but it should be treated cautiously because hidden queries can create N+1 performance problems.
When investigating a navigation property issue, examine the relationship mapping, foreign key values, query shape, loading strategy, context lifetime and generated SQL separately. This method leads to the root cause instead of encouraging unrelated migration or entity changes.