efcore icon indicating copy to clipboard operation
efcore copied to clipboard

EF Core - Disable lazy-loading for some navigation properties

Open andreluizsecco opened this issue 8 years ago • 3 comments

Hello,

I'm testing the lazy loading in EF Core (preview1-final version), leaving it enabled by default in my DbContext.

Ex:

protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder
        .UseLazyLoadingProxies ()
        .UseSqlServer (myConnectionString);

From what I've noticed, this setting forces me to have my navigation properties marked as "virtual". In one of my entities, I have 3 navigation properties, but I want to enable Lazy loading in just two of them (I would not like to implement ILazyLoader, as it would "dirty" my domain). If I'm not mistaken, in EF 6.x this was possible by omitting the "virtual" markup on the navigation property.

In short, I would like to leave Lazy loading enabled, but choose on which property it will work without having to implement ILazyLoader in my entity. Is that already possible? If not, I believe that using the "virtual" markup as the criterion of lazy loading on certain navigation properties would be very good.

Thanks in advance.

andreluizsecco avatar Mar 12 '18 20:03 andreluizsecco

@andreluizsecco Configuration of only specific navigation properties is tracked by #10787, which is currently on the backlog. We don't plan to pivot this behavior using virtual because that was a common source of errors/confusion in classic EF--it's very easy to miss a virtual and not notice.

ajcvickers avatar Mar 12 '18 22:03 ajcvickers

Hi,

Sorry to open this topic again.

I have a problem in this scenario that is when i use the Include method on a lazy property and i store the result in a static cache, like ObjectCache.

The lifetime scope of my application is per request including and the DbContext. So, if i store the result of my query in a static cache with proxy lazy properties, when i refresh the page i get a Microsoft.EntityFrameworkCore.Infrastructure.LazyLoadOnDisposedContextWarning exception. I think that was must be possible to disable the proxies in this scenario to make this works in sub sequents requests. In this case, if i disable the lazy loading, all things works. There is a way to make this running without disable all lazy loading?

marlonbidu avatar Aug 03 '18 17:08 marlonbidu

@marlonbidu I filed #12895 to track this.

ajcvickers avatar Aug 05 '18 21:08 ajcvickers