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)

        return user;

it works correctly only if lazy loading is enabled:

        services.AddDbContext<DataContext>(options => options

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...

12/27/2018 8:03:24 PM

Accepted Answer

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

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

12/27/2018 9:16:34 PM

Popular Answer

You are perhaps misinterpreting the usage of lazy loading, by mentioning that other users can use your service without lazy loading is enabled. The clients will not turn on or off lazy loading, it is up to you that implement the backend to make sure that you check for null navigation properties of EF to be existing or not.

Lazy loading is a general feature in EF Core 2.1 that allows you to load in navigation properties only when they are accessed. These properties must be virtual and the class must not be sealed.

Maybe you are misinterpreting the word "proxies" with a client-service call. Anyways, it is you that implement the backend that must see through that your data model is not inconsistent. Clients cannot turn lazy loading on or off.

If you are not talking about your peers at work that will call the EF code from another layer, such as the data layer. Then you must see through that null checking is done properly. Lazy loading is usually a good thing, but you can do eager loading such as .Include in case you want to load up navigation properties.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow