简体   繁体   English

Entity Framework Core 2.2 嵌套选择生成多个查询

[英]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.当 ToList() 被执行时,属性 LoanStatuses 没有具体化,就像在 EntityFramework 中发生的那样,而是在调用 customer.LoanStatuses 时发送新的查询。

I also tried to add ToList() in .Select method, as suggested on various blogs.我还尝试在 .Select 方法中添加 ToList(),正如各种博客上所建议的那样。 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.效果很好,但是,发送了 2 个查询而不是 1 个(实际上,由于我有 8 个与此类似的集合属性,因此我收到了 9 个查询而不是 1 个。

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?有什么方法可以强制 EF Core 2.2 执行单个查询,并使用所有必需的连接,以便在一次点击中返回所有必需的数据,就像在实体框架的非核心版本中一样?

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?有什么方法可以强制 EF Core 2.2 执行单个查询,并使用所有必需的连接,以便在一次点击中返回所有必需的数据,就像在实体框架的非核心版本中一样?

No. Single query mode has been introduced in EF Core 3.0 . 不可以。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.在 EF Core 2.x 中,您应该在集合投影中使用上述ToList来获取K + 1查询,其中K是相关集合的数量。 This way at least you avoid the N * K + 1 queries (worst) where N is the number of records returned by the main query.这样至少可以避免N * K + 1查询(最差),其中N是主查询返回的记录数。

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.但请注意,对于许多子集合,这实际上比单个查询要好,而 EF Core 3.x 受此影响,尤其是多个集合包含。

That's why EF Core 5.0 will introduce split query option to allow bringing EFC 2.x "multi-query" mode back.这就是 EF Core 5.0 将引入拆分查询选项以允许恢复 EFC 2.x“多查询”模式的原因。

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.总结一下, K + 1查询模式是 EFC 2.x 中最好的,如果你有很多子集合,你最好不要升级到 EFC 3.x,而是等待 EFC 5.x 并保持它模式。

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

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