9/8/12

What is the difference between ObjectSet and EntityCollection?


When working with the Entity framework, you may see that there are two types of collection created, ObjectSet and EntityCollection. Many of us get a bit confused as of why there are two types of collections and about their use. I will try to describe my understanding of their differences:

ObjectSet Definition from MSDN:

public class ObjectSet<TEntity> : ObjectQuery<TEntity>,
        IObjectSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>,
        IQueryable, IEnumerable 
where TEntity : class

ObjectSet provides access to entities/tables of a database.  ObjectSet is IQueryable which means that when you use this reference with a LINQ query, the expression is changed to the SQL expression for the provider (i.e. Entity classes mapping to SQL Server). This is how LINQ works for the LINQ to Entities expressions to be able to select records from the database.

EntityCollection Definition from MSDN:

public sealed class EntityCollection<TEntity> : RelatedEnd, 
        ICollection<TEntity>, IEnumerable<TEntity>, IEnumerable, IListSource 
where TEntity : class

EntityCollection is a collection type which represents “many” entities. When we use LINQ to query an EntityCollection, we are using LINQ to Objects to retrieve the “in-memory” objects in the collection, and no query is executed in the database.  The records for this collection are the ones associated to a main entity as a property and are loaded using the Load method which uses an ObjectSet to load the records from the database. Look at this pseudocode:

VehicleMake: IQueryable{                //represents the ObjectSet
        VehicleModels:IEnumerable      //represents an EntityCollection populated by Load()
}

VehicleModels:IQueryable{// ObjectSet which gets the records from the database
}

When the collection is a property is an EntityCollection.

I hope this is able to help some of you.