I am writing a generic repository for entity framework and am confused as to what the difference between these calls are:
ObjectContext.CreateObjectSet<T>
ObjectContext.CreateQuery<T>
DbContext.Set<T>
I want a generic repository that both supports context generated from .edmx files as well as code first DbContext, so I've got this:
public abstract class EntityRepository<TClass>
where TClass : class, new()
{
//private readonly TContext _context;
private readonly ObjectSet<TClass> _objectSet;
protected EntityRepository(IObjectContextAdapter context)
{
_objectSet = context.ObjectContext.CreateObjectSet<TClass>();
}
protected EntityRepository(ObjectContext context)
{
_objectSet = context.CreateObjectSet<TClass>();
}
public ObjectSet<TClass> Query()
{
return _objectSet;
}
}
In the examples I have seen online I've seen all 3 used, what is the actual differences between them? Is one better performance wise? I know you can write LINQ queries against the contexts using all 3 methods.
The CreateObjectSet<T>
returns you ObjectSet<T>
that's basically collection of T objects, with ability to add, remove, ... object from this collections resulting later to inserts, deletes, ... You can also use it for querying. It's like a top level root for given entity.
The CreateQuery<T>
gives you ObjectQuery<T>
, which can be viewed like IEnumerable<T>
(it's also IQueryable<T>
). This object is like subset of ObjectSet<T>
(some conditions etc.), but you can't add items to it and so on.
And finally the Set<T>
returns DbSet<T>
that's simplified version of first method/object for Code First. It's easier to, for instance, to use these objects (or better to say interfaces; IDbSet<T>
) for i.e. unit testing etc. Similar to what ObjectContext
and DbContext
is.