How to load entities into readonly collections using the entity framework

Posted by Anton P on Stack Overflow See other posts from Stack Overflow or by Anton P
Published on 2010-04-01T04:39:28Z Indexed on 2010/04/01 4:43 UTC
Read the original article Hit count: 253

Filed under:
|
|

I have a POCO domain model which is wired up to the entity framework using the new ObjectContext class.

public class Product
    {
        private ICollection<Photo> _photos;

        public Product()
        {
            _photos = new Collection<Photo>();         
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public virtual IEnumerable<Photo> Photos
        {
            get
            {
                return _photos;
            }
        }

        public void AddPhoto(Photo photo)
        {
            //Some biz logic
            //...
            _photos.Add(photo);
        }
    }

In the above example i have set the Photos collection type to IEnumerable as this will make it read only. The only way to add/remove photos is through the public methods.

The problem with this is that the Entity Framework cannot load the Photo entities into the IEnumerable collection as it's not of type ICollection.

By changing the type to ICollection will allow callers to call the Add mentod on the collection itself which is not good.

What are my options?

© Stack Overflow or respective owner

Related posts about c#

Related posts about framework