简体   繁体   中英

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. Any suggestions?

Try to rewrite your HaveApprovals extension in this way:

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). So SQL know nothing about your extension method and how to execute it.

UPDATE#1:

query below

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

will generate following SQL query

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. The query will be handled by sql so it cannot understand the returned list

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