Beware of IEnumerable with Entity Framework

Standard

Sometimes you want to build a generic data access layer out of your entity framework concrete context, and you want to use the precious generic method on the DbContext such as the generic Set(). If it can spare you some time… Beware than when you do :

         public IEnumerable<T> Get<T>() where T : class
        {
            return _context.Set<T>();
        }

When the function returns, your query is already materialized, the query to the database has been made ! Because the Get function’s return type, IEnumerable, implies an implicit cast to get it from a DbSet. EF is probably making a ToList() inside to transform to IEnumerable, and thus, making the roundtrip to database and materializing objects.

To keep a lazy set, it’s better to switch to  :

       public IQueryable<T> Get<T>() where T : class
        {
            return _context.Set<T>();
        }

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s