简体   繁体   English

在扩展方法中使用扩展方法进行 EF 查询

[英]EF query using extension method inside extension method

I have table Requests, that has Approvals :我有表请求,有批准:

public class Request {
    public virtual List<Approval> Approvals { get; set; } 
}

Requests come from DB请求来自数据库

public DbSet<Request> Request { get; set; }

I have extension method:我有扩展方法:

public static IQueryable<Request> HaveApprovals(this IQueryable<Request> requests) {
    return requests.Where(r => r.ActiveApprovals().Count() > 0).ToList();
}

And another extension method:还有另一种扩展方法:

public static IEnumerable<Approval> ActiveApprovals(this Request request) {
     return request.Approvals.Where(a => !a.Deleted);
}

But getting error:但得到错误:

LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable`1[Domain.Approval] ActiveApprovals(Domain.Request)' method, and this method cannot be translated into a store expression.

For some reason one extension method is able to be translated to LINQ, but when using extension method inside another, then it fails to translate.出于某种原因,一种扩展方法能够转换为 LINQ,但是当在另一种扩展方法中使用扩展方法时,它无法转换。 Any suggestions?有什么建议?

Try to rewrite your HaveApprovals extension in this way:尝试以这种方式重写您的 HaveApprovals 扩展:

public static IQueryable<Request> HaveApprovals(this IQueryable<Request> requests) {
    return requests.Where(r => r.Approvals.Any(a => !a.Deleted)).ToList();
}

Error occurs because EF tries to execute any operation in query on the server side ( SQL server).发生错误是因为 EF 尝试在服务器端(SQL 服务器)上执行查询中的任何操作。 So SQL know nothing about your extension method and how to execute it.所以 SQL 对你的扩展方法以及如何执行它一无所知。

UPDATE#1:更新#1:

query below下面查询

var query = this.DataContext.Products.Where(x => x.Sales.Any(s => s.SectorId == 1));

will generate following SQL query将生成以下 SQL 查询

SELECT [t0].[Id], [t0].[Name], [t0].[Description]
FROM [dbo].[Products] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [dbo].[Sales] AS [t1]
    WHERE ([t1].[SectorId] = @p0) AND ([t1].[ProductId] = [t0].[Id])
    )
}

It will not extract all records so it will not decrease performance.它不会提取所有记录,因此不会降低性能。

Return a Iqueryable or Ienumerable and not a list.返回 Iqueryable 或 Ienumerable 而不是列表。 The query will be handled by sql so it cannot understand the returned list查询将由 sql 处理,因此它无法理解返回的列表

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

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