Skip to content

Query Against Entity Framework or IQueryable Directly

Long Le edited this page Sep 20, 2017 · 2 revisions

We understand that there are teams that would like to query as if they are querying directly from Entity Framework (IQueryable). We recommend that you use the API's from the framework which out of the box return IList, ICollection, IEnumerable, etc. and not IQueryable. Your application will break if you were to switch to a provider that does not support IQueryable e.g. MongoDb (which we are planning on developing), pure REST APIs, etc. For any other common querying methods that the framework APIs don't already cover, the framework is deliberately designed so that you can add your own and return common collections e.g. IList, ICollection, IEnumerable, etc. With this being said if you still have the desire to query directly from IQueryable as you would with Entity Framework or nHibernate.Linq please continue reading.

Every IRepository or IRepositoryAsync has a method (intuitively) named: Queryable, which will return the DbSet, this was intended only to be used for things like ASP.NET Web API OData which requires IQueryable, however you could use it to query against as if your were working directly with Entity Framework.

The pattern is every thing CRUD should be at the Repository layer, and everything with business logic should live in the Services layer. In an ASP.NET MVC application your Controllers should only be injected with IServices, this is the best of the best practices approach and also for Separation of Concerns. The query below should live in ICustomerService, CustomerService and be injected into whatever would be consuming this query.

 var customers = _customerService
                    .Queryable()
                    .Include(t => t
                        .Orders
                        .Select(u => u.OrderDetails))
                    .Where(t => t.CustomerID == key)
                   .OrderBy(t => t.CompanyName)
                   .ThenBy(t => t.ContactName);