1

I want to disable lazy loading in EF Core. Right now I have an infinite loop of loading relations. By running the below code, I get an Employee with all relations to the Employee, even if lazy loading is disabled.

public EmployeeProcess GetByEmployeeNr(int employeeNr)
    {
        if (_db.EmployeeProcess.Any(ep => ep.Employee.Id == employeeNr))
            return _db.EmployeeProcess.First(ep => ep.Employee.Id == employeeNr);
        return null;
    }

To turn of relations I have tried to write the following in the constructor of the context:

this.ChangeTracker.LazyLoadingEnabled = false; 

I have also tried to do it in the repository by using:

db.ChangeTracker.LazyLoadingEnabled = false;

On other posts I have read that Context.Configuration.LazyLoadingEnabled = false, is the way to go, but I have no Configuration in my Context.

The empty constructor looks like this:

public SalRegContext(DbContextOptions<SalRegContext> options) : base(options) { }

Does someone know how to get the configuration, or another solution to prevent the infinite loop of relations?

this.ChangeTracker.LazyLoadingEnabled = false; Does not work..

Context.Configuration.LazyLoadingEnabled = false; is not possible, as there is no configuration.

mrGold
  • 11
  • 3

1 Answers1

0

Disable lazy loading by default in Entity Framework 4

try disabling lazy loading in the EntitiesContext

public MyEntitiesContext() : base("name=MyEntitiesContext", "MyEntitiesContext")
{
    this.ContextOptions.LazyLoadingEnabled = false;
    OnContextCreated();
}

see https://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx

Disable lazy loading by default in Entity Framework 4
(look for a configuration setting that is turning lazy loading on)

EDMX file should be edited by adding the annotation:LazyLoadingEnabled="false"

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
Golden Lion
  • 3,840
  • 2
  • 26
  • 35
  • I don't even use optionsBuilder.UseLazyLoadingProxies().UseSqlServer(connectionString).. I have: ' public void EstablishDbContext(IServiceCollection services, string connectionString) { services.AddDbContext(options => { options.UseSqlServer(Configuration.GetConnectionString(connectionString), o => { o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); }); options.EnableSensitiveDataLogging(); }); } ' – mrGold Nov 23 '22 at 16:37
  • Also we don't use "proxy" anywhere in the code.. We are using EF Core 6.0.. – mrGold Nov 23 '22 at 16:39