Entity collection lazy loading not working

Feb 17, 2015 at 2:04 PM
Hi,

Does this framework support lazy loading of collections? I have the following entities:
public partial class Employee : Entity
    {
        public Employee()
        {
            this.EmployeePositions = new List<EmployeePosition>();
        }
        
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public virtual ICollection<EmployeePosition> EmployeePositions { get; set; }
    }

public partial class Position : Entity
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool ClockInOut { get; set; }
    }

public class EmployeePosition : Entity
    {
        public int Id { get; set; }

        public virtual Employee Employee { get; set; }

        public virtual Position Position { get; set; }

        public bool Enabled { get; set; }
        public decimal HourlyPay { get; set; }
    }
From the following tests, the first one passes but the second one fails.
[TestMethod]
        public void Can_Insert_Postions_For_Employee()
        {
            Employee entity = _employeeService.Find(1);

            var positions = _positionService.Queryable();

            foreach (var position in positions)
            {
                var employeePostion = entity.EmployeePositions.Where(p => p.Position.Id == position.Id).SingleOrDefault();

                if (employeePostion == null)
                {
                    EmployeePosition ep = new EmployeePosition
                    {
                        Enabled = false,
                        HourlyPay = 0,
                        Employee = entity,
                        Position = position
                    };
                    _employeePositionService.Insert(ep);
                }
            }

            _unitOfWork.SaveChanges();

            Assert.IsTrue(_employeePositionService.Queryable().Where(e => e.Employee.Id == entity.Id).Count() == 2);
        }

        [TestMethod]
        public void Employee_Has_2_Positions()
        {
            Employee entity = _employeeService.Find(1);
            Assert.IsTrue(entity.EmployeePositions.Count == 2);
        }
Upon debugging, it seems the EmployeePositions collection of the Employee class is always zero.

Is there something wrong with my design?
Coordinator
Mar 12, 2015 at 9:16 AM
Yes, please make sure it's enabled in your DbContext.

e.g.
public class BloggingContext : DbContext 
{ 
    public BloggingContext() 
    { 
        this.Configuration.LazyLoadingEnabled = true; 
    } 
}
Marked as answer by lelong37 on 3/12/2015 at 1:16 AM