Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between .CreateObjectSet<T>, .Set<T>, and .CreateQuery<T>?

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.

like image 201
SventoryMang Avatar asked Jan 20 '12 20:01

SventoryMang


2 Answers

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.

like image 159
cincura.net Avatar answered Nov 03 '22 02:11

cincura.net


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).

like image 42
divega Avatar answered Nov 03 '22 00:11

divega