What are the distinctions between.CreateObjectSetT>,.SetT>, and.CreateQueryT>?

datacontext entity-framework generics

Question

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.

1
10
1/13/2014 6:29:52 PM

Accepted Answer

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.

16
1/21/2012 6:13:23 AM

Popular Answer

In addition to what Jiri already explained, there is an overload of CreateObjectSet that takes no arguments. This overload will automatically assume that it has to return the ObjectSet for the only EntitySet associated with TEntity. It will throw if the model has MEST (multiple-entity-sets-per-type). All overloads of CreateQuery need an Entity SQL string to bootstrap the query (note that the name of an EntitySet is a valid Entity SQL query).



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow