Tag Archives: Entity framework

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