CodexBloom - Programming Q&A Platform

Unexpected Behavior with Entity Framework Core 6 Lazy Loading and Navigation Properties

👀 Views: 65 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
entity-framework-core lazy-loading c# ef-core-6 navigation-properties C#

I'm trying to figure out I'm migrating some code and I've tried everything I can think of but I'm converting an old project and I'm stuck on something that should probably be simple. I'm encountering unexpected behavior with lazy loading in Entity Framework Core 6. I have a scenario where I'm trying to access a navigation property on a retrieved entity, but it seems like the navigation properties are not being loaded as expected. My model looks something like this: ```csharp public class Order { public int Id { get; set; } public virtual ICollection<OrderItem> Items { get; set; } } public class OrderItem { public int Id { get; set; } public int OrderId { get; set; } public virtual Order Order { get; set; } } ``` I have also configured my `DbContext` like this: ```csharp public class MyDbContext : DbContext { public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>() .HasMany(o => o.Items) .WithOne(i => i.Order) .HasForeignKey(i => i.OrderId); } } ``` When I retrieve an `Order` with lazy loading enabled, I expect the `Items` collection to be automatically populated: ```csharp using (var context = new MyDbContext()) { var order = context.Orders.Find(1); var itemCount = order.Items.Count; // I expect this to be greater than 0 } ``` However, `itemCount` is always returning 0, and I don't see any related SQL queries in the logs. I've checked that lazy loading is enabled in the context configuration: ```csharp services.AddDbContext<MyDbContext>(options => { options.UseLazyLoadingProxies(); options.UseSqlServer(connectionString); }); ``` I've also tried explicitly including the `Items` collection using `.Include(o => o.Items)` and that works fine, so it seems like lazy loading is not functioning as intended. I've confirmed that the `Order` entity is being tracked by the context. Is there something I'm missing, or some specific configuration that I need to do to get lazy loading to work correctly with navigation properties in EF Core 6? What am I doing wrong? I'm using C# 3.9 in this project. For reference, this is a production web app. I appreciate any insights! For reference, this is a production application. Any ideas how to fix this?