简体   繁体   English

在另一个 IQueryable 中使用一个 IQueryable

[英]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,我有一个扩展方法,它返回一个 IQueryable,以获取公司产品,我只想在 IQueryable 中将它用作子查询,

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?我希望它能工作,因为我的扩展方法返回一个 IQueryable,所以它可以在 IQueryable 中使用,我错了吗?

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. System.NotSupportedException: LINQ to Entities 无法识别方法 'System.Linq.IQueryable`1[WebProject.Models.Company] GetCompanyProducts(WebProject.Models.DBEntities, Int32)' 方法,并且此方法无法转换为存储表达式.

Problem is not IQueryable inside IQueryable , because you can include subqueries just not the way you did.问题不在IQueryable内部的IQueryable中,因为您可以包含子查询,而不是像您那样做。

In your example whole Select is represented as expression tree.在您的示例中,整个Select表示为表达式树。 In that expression tree there is something like:在那个表达式树中有类似的东西:

CALL method DBEntitiesCompanyExtensions.GetCompanyProducts

Now EF should somehow traslate this into SQL SELECT statement.现在 EF 应该以某种方式将其翻译成 SQL SELECT 语句。 It cannot do that, because it cannot "look inside" GetCompanyProducts method and see what is going on there.它不能那样做,因为它不能“查看” GetCompanyProducts方法并查看那里发生了什么。 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的事实无济于事,也不相关。

Instead of using IQueryable you should create an expression predicate and use inside the IQueryable object that is connected to the data source而不是使用 IQueryable 你应该创建一个表达式谓词并在连接到数据源的 IQueryable object 中使用

the object looks like that: object 看起来像这样:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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