简体   繁体   中英

Entity Framework Core 2.2 nested select generates multiple queries

I have a query similar to this:

var customers = dbContext.Customers.Select(c => new 
                {
                    FirstName = c.FirstName,
                    LoanStatuses = c.LoanRequests.Select(l => l.Status)
                }).ToList();

When ToList() is executed, the property LoanStatuses is not materialized, like it happens in EntityFramework, but instead new queries are sent when customer.LoanStatuses is called.

I also tried to add ToList() in .Select method, as suggested on various blogs. That works well, however, 2 queries are sent instead of one (actually, since I have 8 collection properties similar to this, I get 9 queries instead of one.

Is there any way to force EF Core 2.2 to perform a single query, with all the required joins in order to return all the required data in a single hit, like in non core versions of Entity Framework?

Is there any way to force EF Core 2.2 to perform a single query, with all the required joins in order to return all the required data in a single hit, like in non core versions of Entity Framework?

No. Single query mode has been introduced in EF Core 3.0 .

In EF Core 2.x you should use the aforementioned ToList in collection projections to get K + 1 queries, where K is the number of the correlated collections. This way at least you avoid the N * K + 1 queries (worst) where N is the number of records returned by the main query.

But note that for many sub collections this actually is better than single query, and EF Core 3.x suffers from that, especially with multiple collection includes.

That's why EF Core 5.0 will introduce split query option to allow bringing EFC 2.x "multi-query" mode back.

To recap, K + 1 query mode is the best you can get in EFC 2.x, and if you have many sub collections, you'd better not upgrade to EFC 3.x, but wait for EFC 5.x and keep that mode.

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