Why is an ICollection required for lazy loading in the entity framework?

domain-driven-design entity-framework lazy-loading

Question

I'd want to create a rich domain class like

public class Product    
{    
   public IEnumerable<Photo> Photos {get; private set;}    
   public void AddPhoto(){...}    
   public void RemovePhoto(){...}
 }

But in order to support slow loading, the entity framework (V4 code first approach) needs an ICollection type! Since clients may call the add method on ICollection instead of the AddPhoto or RemovePhoto methods, the code above no longer functions as intended. Not good at all.

public class Product    
{    
   public ICollection<Photo> Photos {get; private set;} //Bad    
   public void AddPhoto(){...}    
   public void RemovePhoto(){...}    
 }

Attempting to use the EF4 and DDD to implement is becoming really challenging. The ICollection was chosen for lazy loading; why?

How can I get beyond this? Do I have a better DDD experience with NHibernate?

1
26
5/19/2010 3:21:55 PM

Popular Answer

I believe I've discovered the answer. For further information, go here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/47296641-0426-49c2-b048-bf890c6d6af2/

To put it simply, you want to secure the ICollection type and utilize it as the backup collection for the open 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(){...}

} 

The type must implement ICollection for lazy loading to function, and the access must be either public or protected.

21
5/20/2010 1:49:40 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow