简体   繁体   中英

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.

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.

Instead of using IQueryable you should create an expression predicate and use inside the IQueryable object that is connected to the data source

the object looks like that:

Expression<Func<Person, bool>> predicate = x => x.Name == "Adi";

var data = await queryable.Where(predicate).ToListAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM