Search code examples
entity-framework-4ef4-code-only

Is it possible to map a collection of value objects with EF4.x?


I can't find a way to map a value object collection, is it possible?

public class AnEntity
{
    public int Id {get;set;}
    public ICollection<Guid> Values {get;set;} // <-- this
}

Thanks, E.


Solution

  • Because it is not possible. You can map only collection of entities (classes with key). You can solve this by using special entity and exposing second property which will provide projection for you:

    public class SecondEntity {
        public Guid Id { get; set; }
    }
    
    public class AnEntity {
        public int Id { get; set; }
        public virtual ICollection<SecondEntity> Values { get; set; }
    
        public IEnumerable<Guid> GuidValues { 
            return Values.Select(v => v.Id);
        }
    }
    

    If you expect that collection will be small you can also use single string field instead of related collection and use String.Split, String.Join to provide emulation of collection.