Using an IQueryable in another IQueryable

十年热恋 提交于 2019-12-31 04:38:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43201599/using-an-iqueryable-in-another-iqueryable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!