Search code examples
c#entity-framework-corelazy-loadingentity-framework-core-2.1

Check if lazy loading is enabled


I have the following model:

public partial class User
{
    // other properties

    /// <summary>
    /// Gets or sets user roles
    /// </summary>
    public virtual IList<UserRole> UserRoles
    {
        get => _userRoles ?? (_userRoles = UserUserRoleMappings.Select(mapping => mapping.UserRole).ToList());
    }

    /// <summary>
    /// Gets or sets user-user role mappings
    /// </summary>
    public virtual ICollection<UserUserRoleMapping> UserUserRoleMappings
    {
        get => _userUserRoleMappings ?? (_userUserRoleMappings = new List<UserUserRoleMapping>());
        protected set => _userUserRoleMappings = value;
    }
}

and method of service in another library:

    public virtual User GetUserByUsername(string username)
    {
        if (string.IsNullOrWhiteSpace(username))
            return null;

        var user = _dbContext.Users
            .Where(u => u.Username == username)
            .FirstOrDefault();

        return user;
    }

it works correctly only if lazy loading is enabled:

        services.AddDbContext<DataContext>(options => options
            .UseLazyLoadingProxies()
            .UseSqlServer(connString));

if lazy loading is not enabled then Users property is not filled. I want to throw an exception, if somebody try to use my service without enabled lazy loading. How to do it? I tried to check property _dbContext.ChangeTracker.LazyLoadingEnabled, but this property is always true, even I did not enable lazy loading...


Solution

  • I found the solution (thank you Tore Aurstad for hint). I override OnConfiguring method in my DbContext :

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLazyLoadingProxies(true);
            base.OnConfiguring(optionsBuilder);
        }
    

    Then we not need to use UseLazyLoadingProxies() method in startup class for enabling Lazy Loading