Home

Disable LazyLoading in EFCore driver

edited November 2018
Is it possible to avoid using LazyLoading with the EFCore driver? The reason this is needed is that lazy-loading is not supported for detached entities, so, for example, if a query uses an extension method for an entity that accesses its "navigation" property, an exception is thrown.

Comments

  • Another reason to disable LazyLoading is that it doesn't support AsNoTracking, which is often used in production apps, so LINQPad can't be used to quickly debug a real query by just copy/pasting anymore.
  • I ended up using an env. variable and conditionally enabling lazy loading proxies in my DB context. This is still less than ideal though since it requires restarting LINQPad after each change. It would be much better if we had a switch in the driver setup dialog.
  • You could probably achieve this as follows: In the connection properties, click the option "via a constructor that accepts a string", and enter a string like "NoLazyLoading". Then put the following code into your data context class:
    string _options;
    public BloggingContext (string options)
    {
      _options = options;
    }
    protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder)
    {
      if (!_options.Contains ("NoLazyLoading"))
         optionsBuilder.UseLazyLoadingProxies();
    
      // If you also want to specify a connection string in your options:
      optionsBuilder.UseSqlServer(_options.Replace ("NoLazyLoading", ""));
      ...
    }
Sign In or Register to comment.