CodexBloom - Programming Q&A Platform

Entity Framework Core - Issues with Lazy Loading in a Multi-Tenant Application

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
entity-framework-core lazy-loading multi-tenant C#

I'm upgrading from an older version and I'm prototyping a solution and Quick question that's been bugging me - I'm currently working on a multi-tenant application using Entity Framework Core 6, and I've run into issues with lazy loading. I have defined my entities with virtual navigation properties, but it seems that the related entities are not being loaded when I access them. Instead, I'm getting a `null` reference. I have set up the proxy creation in my `DbContext`: `this.Configuration.ProxyCreationEnabled = true;`, but it doesn't seem to be effective. Here's a simplified version of my entity classes: ```csharp public class Tenant { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<User> Users { get; set; } } public class User { public int Id { get; set; } public string UserName { get; set; } public int TenantId { get; set; } public virtual Tenant Tenant { get; set; } } ``` In my service, when I query the `Tenant` and include the users like this: ```csharp var tenant = await _context.Tenants .FirstOrDefaultAsync(t => t.Id == tenantId); ``` I expected that `tenant.Users` would be populated lazily when accessed. However, when I try to access `tenant.Users`, it returns `null`. I've tried enabling lazy loading with `services.AddDbContext<MyDbContext>(options => options.UseLazyLoadingProxies())`, and I have verified that my navigation properties are marked as virtual, but I still face this issue. Additionally, I'm noticing that the loading behavior is inconsistent depending on whether I'm retrieving the tenant in isolation or as part of a larger query. Can anyone provide insight into how to properly configure lazy loading in this multi-tenant setup, or if there are best practices I should be aware of? Is there a potential issue with the way the DbContext is being instantiated or used across different services? Any advice would be greatly appreciated! This is part of a larger API I'm building. Thanks in advance! Am I missing something obvious? For context: I'm using C# on Debian. Any help would be greatly appreciated! Am I approaching this the right way?