首页 > 解决方案 > Entity Framework Core - 我可以直接查询子属性中的列表/对象,避免多次重复 Include/ThenInclude 吗?

问题描述

在我们的后端,我们有一个 LINQ 查询来检索给定购买的客户信息,例如:

var serviceRequest = await _dbContext.Purchases
    .Include(p => p.Customer)
      .ThenInclude(c => c.Addresses)
    .Include(p => p.Customer)
      .ThenInclude(c => c.EmailAddresses)
    .Include(p => p.Customer)
      .ThenInclude(c => c.PhoneNumbers)

我们想重构它并避免重复

Include(p=>p.blablabla)

每当我们想添加更多东西来检索时。所以我们的目标是将这个原始的 LINQ 修改为

var serviceRequest = await _dbContext.Purchases
    .Include(p => p.Customer.Addresses)
    .Include(p => p.Customer.EmailAddresses)
    .Include(p => p.Customer.PhoneNumbers)

使用 SQL 分析器,我们观察到 EFCore 生成的查询是相同的,并且明显的结果对象是相似的,所以我们的问题是:有没有一种方法、最佳实践或理由来使用多个 Include 和 ThenInclude,即使是第二个选项我们认为是否更清晰易读?急切加载(我们默认使用)是否有副作用?

标签: c#sql.net-coreentity-framework-coreeager-loading

解决方案


你做的一切都是正确的。如果它们跟随在 one-to-many 之后,那么 ThenLoad 很有用Include

关于副作用:一切都应该正常工作或 EF Core 团队打破了这一点;)记录在案,例如这里:https ://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.entityframeworkqueryableextensions.include?view =efcore-3.1但作为字符串属性路径,应该是一样的。


推荐阅读