Andrew
Andrew

Reputation: 2011

EF 6.1.3 Lazy loading not working

I am trying to get a single employee record, but looking at the Diagnostic Tools it is showing Entity Framework performing tons of queries loading the entire database. Lazy loading is enabled and I am using the public and virtual keywords so I don't think that should be the problem. Is there anything I am missing, the navigational properties for the Employee record should not be loading.

Service:

return _employeeRepo.GetEmployee(sid);

Repository:

public Employee GetEmployee(string sid)
    {
        Employee employee = Context.Employees.SingleOrDefault(e => e.SID == sid);

        return employee != null ? employee.ToDomain() : null;
    }

Employee Model:

public class Employee
{
    ...
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Disability> Disabilities { get; set; }
    ...
    public virtual Bureau Bureau { get; set; }
    public virtual Division Division { get; set; }
    ...

    public Domain.Models.Employee ToDomain()
    {
        return Mapper.Map<Domain.Models.Employee>(this);
    }
}

Context:

public class SqlContext : DbContext
{
    public SqlContext() : base("SqlContext")
    {
        Database.SetInitializer<SqlContext>(null);
    }

    public virtual DbSet<EfModels.Address> Addresses { get; set; }
    public virtual DbSet<EfModels.Bureau> Bureaus { get; set; }
    public virtual DbSet<EfModels.Disability> Disabilities { get; set; }
    public virtual DbSet<EfModels.Division> Divisions { get; set; }
    public virtual DbSet<EfModels.Employee> Employees { get; set; }
}

Upvotes: 0

Views: 323

Answers (1)

Derek
Derek

Reputation: 8630

Your Mapping Tool (AutoMapper) is the issue.

When your calling employee.ToDomain(), the navigation properties of your entity are being accessed, causing EF to lazy load the tables.

Upvotes: 1

Related Questions