Why does the entity framework need an ICollection for lazy loading?

I think i found the solution…See here for more details: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/47296641-0426-49c2-b048-bf890c6d6af2/

Essentially you want to make the ICollection type protected and use this as the backing collection for the public IEnumerable

public class Product
{

   // This is a mapped property
   protected virtual ICollection<Photo> _photos { get; set; }

   // This is an un-mapped property that just wraps _photos
   public IEnumerable<Photo> Photos
   {
      get  { return _photos; }
   }

   public void AddPhoto(){...}
   public void RemovePhoto(){...}

} 

For lazy loading to work the type must implement ICollection and the access must be public or protected.

Leave a Comment