CodexBloom - Programming Q&A Platform

EF Core 6 - Lazy Loading Not Working with Navigation Properties in Inherited Entities

👀 Views: 162 💬 Answers: 1 📅 Created: 2025-09-06
entity-framework-core lazy-loading inheritance C#

I'm updating my dependencies and I tried several approaches but none seem to work. I'm working with Entity Framework Core 6 and I have a scenario where I’m trying to use lazy loading for navigation properties in a base class, but it doesn’t seem to work with derived classes. I followed the standard procedure by marking my navigation properties as virtual and configured my DbContext accordingly. Here’s a simplified example of my entities: ```csharp public class Person { public int Id { get; set; } public string Name { get; set; } } public class Employee : Person { public string Position { get; set; } public virtual Department Department { get; set; } } public class Department { public int Id { get; set; } public string DepartmentName { get; set; } } ``` And my DbContext is set up like this: ```csharp public class MyDbContext : DbContext { public DbSet<Person> People { get; set; } public DbSet<Employee> Employees { get; set; } public DbSet<Department> Departments { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Employee>() .HasOne(e => e.Department) .WithMany() .HasForeignKey("DepartmentId"); } } ``` I have enabled lazy loading by calling `UseLazyLoadingProxies()` in my `OnConfiguring` method: ```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder .UseLazyLoadingProxies() .UseSqlServer("YourConnectionString"); } ``` When I try to access the `Department` property of an `Employee` instance, I get a `NullReferenceException`. Here’s how I’m accessing it: ```csharp using (var context = new MyDbContext()) { var employee = context.Employees.FirstOrDefault(); Console.WriteLine(employee.Department.DepartmentName); } ``` The `Department` property doesn’t seem to be loaded, even though it should be lazy-loaded. I’ve confirmed that the foreign key relationship is set up correctly in the database, and I’m not encountering any warnings during migrations. Any insights on what I might be missing or what could be preventing the lazy loading from functioning as expected? I am also using SQL Server 2019 and have the latest EF Core packages installed. Thanks in advance for any help! For context: I'm using C# on Windows. I'm using C# 3.10 in this project. Any suggestions would be helpful.