How to properly trigger lazy load of collection in Entity Framework 5?

.net, c#, entity-framework, entity-framework-5

Solution

In order for lazy-loading to work, EF5 has to do some tricky work. At runtime they create proxy-classes, which are derived from your model classse. Within these proxy classes they override the navigation properties to implement the lazy-loading mechanism.

Your `SubEntity2` and `SubEntity3` properties are virtual, so they can be overridden. Your `SubEntities` property is not virtual - EF5 can't override this property to implement lazy loading for it.

When you make your `SubEntities` property virtual it should work.

Problem

I'm using EF5 (code first) in my application. I have a table which contains a few lazy loading fields. ``` public class TestEntity { public int Id { get; set; } public virtual TestEntity2 SubEntity2 { get; set; } public virtual TestEntity3 SubEntity3 { get; set; } private ICollection<SubEntity4> _subEntities; public ICollection<SubEntity4> SubEntities { get { return _subEntities ?? (_subEntities = new Collection<SubEntity4>()); } protected set { _subEntities = value; } } } ``` When I'm reading this from database SubEntity2 and SubEntity3 are loading fine but SubEntities collection just won't load and it's always stay Count=0. So I'm forcing load like this: ``` db.Entry(queryResult).Collection(rr => rr.SubEntities).Load(); ``` But as I understand this collection should be loaded automatically by EF during the first invocation just like SubEntity2 and SubEntity3. Why isn't it working with collection? Example of the code I'm using to read database: ``` using (var db = new TestContext(_connection, false)) { var query = from r in db.SubEntities where r.Id == 10 select r; var queryRes = query.FirstOrDefault(); if (queryRes != null) { if (queryRes.FederalRegion != null) { // Do something } foreach (var dbEnt in queryRes.SubEntities) { // Do something } } } ```

Original source