在另一个IQueryable中使用IQueryable [英] Using an IQueryable in another IQueryable
问题描述
我有一个扩展方法,它返回一个IQueryable,以获取公司产品,我只想在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);
}
}
这就是我的称呼,
using(var db = new DBEntities()) {
var query = db.Companies.Select(m => new {
CompanyName = m.Name,
NumberOfProducts = db.GetCompanyProducts(m.CompanyId).Count()
});
}
我希望它能起作用,因为我的扩展方法返回了一个IQueryable,因此可以在IQueryable中使用它,对吗?
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无法识别 方法'System.Linq.IQueryable`1 [WebProject.Models.Company] GetCompanyProducts(WebProject.Models.DBEntities,Int32)' 方法,并且该方法不能转换为商店表达式.
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.
推荐答案
问题不在IQueryable
内的IQueryable
内,因为您可以包括子查询,而不能像以前那样包含子查询.
Problem is not IQueryable
inside IQueryable
, because you can include subqueries just not the way you did.
在您的示例中,整个Select
被表示为表达式树.在该表达式树中,有一些类似的内容:
In your example whole Select
is represented as expression tree. In that expression tree there is something like :
CALL method DBEntitiesCompanyExtensions.GetCompanyProducts
现在,EF应该以某种方式将其转换为SQL SELECT语句.它无法做到这一点,因为它无法查看内部" GetCompanyProducts
方法并查看发生了什么.它也不能执行此方法并对结果执行任何操作.它返回IQueryable
的事实无济于事,并且不相关.
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.
这篇关于在另一个IQueryable中使用IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!