CodexBloom - Programming Q&A Platform

How to implement guide with entity framework core 6 and lazy loading causing null reference exceptions

πŸ‘€ Views: 50 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-23
entity-framework-core lazy-loading null-reference-exception C#

I'm working with Entity Framework Core 6 in a .NET 6 application and I'm working with a frustrating scenario with lazy loading. I have an `Order` entity that has a navigation property to a `Customer` entity. When I try to access the `Customer` property of an `Order` object after retrieving it from the database, I sometimes get a `NullReferenceException`. Here’s the code I’m using: ```csharp public class Order { public int Id { get; set; } public int CustomerId { get; set; } public virtual Customer Customer { get; set; } } public class Customer { public int Id { get; set; } public string Name { get; set; } } var order = await _context.Orders.FindAsync(orderId); var customerName = order.Customer.Name; // Throws NullReferenceException ``` I have enabled lazy loading by configuring it in `Startup.cs` like this: ```csharp services.AddDbContext<MyDbContext>(options => { options.UseLazyLoadingProxies(); options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); }); ``` I’ve double-checked that the relationship is correctly set up in the database, and I can confirm that the `Order` entity does have a corresponding `Customer` in the database. I've attempted to manually include the `Customer` using the `Include` method, which works, but I need to rely on lazy loading in certain scenarios. What could be causing this scenario? Is there a specific setting or best practice I’m missing that could help avoid these null reference exceptions?