Search code examples
c#linqlinq-to-entitiesiqueryable

Using an IQueryable in another IQueryable


I've an extension method, which returns an IQueryable, to get company products, I just want to use it in a IQueryable as a subquery,

public static class DBEntitiesCompanyExtensions {
   public static IQueryable<Product> GetCompanyProducts(this DBEntities db, int companyId)
   {
      return db.Products.Where(m => m.CompanyId == companyId);
   }
}

And this is how I call it,

using(var db = new DBEntities()) {
   var query = db.Companies.Select(m => new {
                CompanyName = m.Name,
                NumberOfProducts = db.GetCompanyProducts(m.CompanyId).Count()
   });    
}

I expected it to works beacuse my extension methods returns an IQueryable, so it could be used in a IQueryable, am I wrong?

This is what I get, Is that possible to make it work?

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[WebProject.Models.Company] GetCompanyProducts(WebProject.Models.DBEntities, Int32)' method, and this method cannot be translated into a store expression.


Solution

  • Problem is not IQueryable inside IQueryable, because you can include subqueries just not the way you did.

    In your example whole Select is represented as expression tree. In that expression tree there is something like :

    CALL method DBEntitiesCompanyExtensions.GetCompanyProducts
    

    Now EF should somehow traslate this into SQL SELECT statement. It cannot do that, because it cannot "look inside" GetCompanyProducts method and see what is going on there. Nor can it execute this method and do anything with it's result. The fact it returns IQueryable does not help and is not related.