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

前端 未结 3 1496
醉酒成梦
醉酒成梦 2020-12-01 11:56

I want to write a rich domain class such as

public class Product    
{    
   public IEnumerable Photos {get; private set;}    
   public void A         


        
相关标签:
3条回答
  • 2020-12-01 12:38

    You can't insert into an IEnumerable. This applies to the EF just as much as it does to your clients. You don't have to use ICollection, though; you can use IList or other writeable types. My advice to get the best of both worlds is to expose DTOs rather than entities to your clients.

    0 讨论(0)
  • 2020-12-01 12:41

    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.

    0 讨论(0)
  • 2020-12-01 12:46

    You can overcome this by using the ReadOnlyCollection(Of T)

    public class Product    
    {  
        private IList<Photo> _photos;  
        public IList<Photo> Photos {
            get
            {
                return _photos.AsReadOnly();
            }
            private set { _photos = value; }
        }
        public void AddPhoto(){...}    
        public void RemovePhoto(){...}    
    }
    

    EDIT: ICollection<T> => IList<T>

    Hope that is what you were looking for.

    0 讨论(0)
提交回复
热议问题